It is likely that we will want the program to do something even when an if statement evaluates to false. In our grade example, we will want output whether the grade is passing or failing.
To do this, we will add an else statement to the grade condition above that is constructed like this:
grade = 60 if grade >= 65: print("Passing grade") else: print("Failing grade")
Since the grade variable above has the value of 60, the if statement evaluates as false, so the program will not print out Passing grade. The else statement that follows tells the program to do something anyway.
When we save and run the program, we will receive the output:
If we then rewrite the program to give the grade a value of 65 or higher, we will instead receive the output Passing grade.
To add an else statement to the bank account example, we rewrite the code like this:
balance = 522 if balance < 0: print("Balance is below 0, add funds now or you will be charged a penalty.") else: print("Your balance is 0 or above.")
Here, we changed the balance variable value to a positive number so that the else statement will print. To get the first if statement to print, we can rewrite the value to a negative number.
By combining an if statement with an else statement, you are constructing a two-part conditional statement that will tell the computer to execute certain code whether or not the if condition is met.
Write a program that asks an age and tells them if they are allowed to see an age 12 film or not.
Write a program that asks an age and tells them if they were born before or after 2000.
Write a program that asks a boolean question and tells them if they were right or wrong.
Thanks [name] from [whichclass][location], Mr McG will get your message…"
[message]"…and will get back to you ASAP via [email]. Catch you soon.
Have a great day!!
K McGuinness - 2018
No personal data will be shared with any third party. The only data processed via this website is anonymous browsing data to best manage your user experience.