ELSE Statement

An introduction to the use of Selection in Python

ELSE Statement

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:

Failing grade

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.")
Show Output
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.

Introduction

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.

9.2 ELSE Statement Task
Submit your completed task...
If you need to get in touch with Mr McG then this is the way….

What's your name?
image/svg+xml
Thank you [name], that's great.

Can I ask where you are from?
image/svg+xml
Hey [name], can I ask where you are from?
image/svg+xml
Hey [name], which class are you in?
image/svg+xml
OK [name], thanks for that.

I will need your email address so I can get back to you!!
image/svg+xml
Thanks [name], nearly there.

What can I help you with?
image/svg+xml

Thanks [name] from [whichclass][location], Mr McG will get your message…"
[message]"…and will get back to you ASAP via [email]. Catch you soon.

image/svg+xml
Thank you [name], Mr McG got your message.
Thanks [name], Mr McG will get back to you as soon as he can!!

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.