Sometimes you will change what do you depending on the conditions.
For example: IF you wake up in the morning and it is raining THEN you will take a coat to school OTHERWISE you wont.
IF the day is a Saturday AND the alarm clock goes off THEN you might turn it off and stay in bed OTHERWISE you might get up.
Life is full of decisions that you will make depending on certain conditions, computers are no different.
if-else
For a computer to make decisions based on a condition, you must use an IF statement, it has the following structure:
Consider the following IF statement:
The IF statement explained:
- after the
if
is the conditionage >= 18
followed by a colon, this is checking to see if the age variable is more than or equal to 18. - after that line is code is the code that will only be run if that condition is
True
. If it is true it will print on screenYou are an adult
. - the word else then follows followed by a colon. The instructions underneath this are what will be run only if that condition is
False
. If it is false it will print on screenYou are still a child
.
if-elif-else
An IF statement with an else will only allow you to check a single condition, however if you have more than one condition to check you can use if..elif..else
Consider the following IF statement:
The IF statement explained:
- the program first checks to see if the colour entered is
Red
and if it is will printSTOP
. - if the colour entered isn’t red it will go onto the next condition where the
elif
is and check if the colour isAmber
. If it is then it will printGET READY TO STOP
- if neither conditions are met it will go to the
else
part of the code and printGO
.
NOTE: It doesn’t need to use elif
to see if the colour is Green
as if it isn’t Red
or Amber
it must be Green
, therefore you can just use else
if there are not other options to consider.
Example program 1 - Capital City
The code for the program below ask the user the capital city of England and display a suitable message depending on whether they enter London
.
When run in IDLE:
Example program 2 - Grade Calculator Program
The code for the program below will ask the user to enter a score on a test and then decide what grade they got.
NOTE: When elif
is used it will only check the next condition if
the previous condition is false.
When run in IDLE:
Example program 3 - Taxi Fare Calculator Program
The code for the program below will calculate the fare for a taxi ride depending on the distance and number of passengers. It should add 50% onto the total if there are more than 5 passengers.
Important Points to Note
- there is no
else
on this - the
print
code is not indented, this is because it is not part of theif
and will display regardless of whether there are more than 5 passengers. - in the
print
command the cost is formatted to currency, this is done by writing£{:.2f}".format(variable)
When run in IDLE: