Making decisions using “if”
We get Python to make decisions about what code to run on the basis of the
False comparisons we were creating above. The “if” statement allows us to say to Python “if the answer to the comparison is True, then run this optional code”.
Here’s an example:
sister_age = 15 brother_age = 12 if sister_age > brother_age: print("Sister is older")
We can also tell Python to run some alternative code if the comparison was not true. That would look like:
sister_age = 15 brother_age = 12 if sister_age > brother_age: print("Sister is older") else: print("Brother is older")
Using this example, what happens if they are the same age? Change the above to make the brothers age also 15. What will it print?
The problem is in the way we framed the options we gave Python. We only gave it two options to choose from. If the sister is older than the brother, it will print “Sister is older” and in every other circumstance it will print “Brother is older”. If they are both 15, however, what we really want is for Python to tell us they are both the same age.
sister_age = 15 brother_age = 15 if sister_age > brother_age: print("Sister is older") elif: sister_age == brother_age: print("Ages are the same! They might be twins!") else: print("Brother is older")
We are now giving Python a series of questions to run through. The work flow looks like this:
- If the sisters age is greater than the brothers age, print “Sister is older” then skip the rest of the “if” stuff
- Otherwise, if the sister age is the same as the brothers age, print “Ages are the same” and then skip the rest of the “if” stuff.
- Otherwise, if nothing has been true yet, print “Brother is older”
The general rule is:
if comparison_is_true: do_something elif alternative_comparison_is_true: do_this_instead else: do_this_if_nothing_has_been_true carry_on_with_other_stuff
- The “do_something” bits can be one line or 100 lines of code.
- You can have an “if” inside an “if” inside an “if” etc!
- You can have as many “elif” as you like
- The level of indentation must be the same throughout!
Common mistake: Indentation matters!
Python uses the indentation to determine which code to run as part of an if/elif/else. Whenever you use a python command that ends with a colon (“:”), that is the hint you need to indent the next line. Continue indenting until you want to stop the conditional section of code. Whenever you indent, the number of spaces used indent must match from line to line. When you have finished, you must return to the previous level of indentation that was being used before.
Here’s another example that shows you can have an unending number of elif questions in your “if” statement.
(don’t worry about the first two lines. As you can probably work out, they are Python code that accesses the date and stores the current day of the week as a number between 0 and 6)
from datetime import datetime day_of_week = datetime.now().weekday() if day_of_week == 0: print("Today is Monday") elif day_of_week == 1: print("Today is Tuesday") elif day_of_week == 2: print("Today is Wednesday") elif day_of_week == 3: print("Today is Thursday") elif day_of_week == 4: print("Today is Friday") elif day_of_week == 5: print("Today is Saturday") elif day_of_week == 6: print("Today is Sunday")
Exercise: Which number is bigger?
How could we create a program that asked for two numbers and gave one of three different answers?
- The first number is bigger
- The second number is bigger
- The numbers are the same
Hint: The start of it is…
num1 = int( input("Type a number: ") ) num2 = int( input("Type another number: ") ) if num1 == num2: print("The numbers are the same")
Exercise: Too hot or too cold?
Suppose you ask the user what the temperature is. Create a program that will respond as follows: If the temperature is between 20 and 27, say that it is “Just right” If the temperature is below 20, say that it is “too cold” * If the temperature is above 27, say that it is “too hot”
Exercise: Age calculator
I previously got you to use some Python date code to find the day of the week. This exercise will give you the current day, month and year so you can use it to calculate someone’s age.
- Can you get it to work?
- Can you add code to wish the user a Happy Birthday if it is their birthday?
from datetime import datetime d = datetime.now().day m = datetime.now().month y = datetime.now().year birthdate = input("Enter your date of birth as dd.mm.yyyy >") dot1 = birthdate.index(".") dot2 = birthdate.rindex(".") my_day = int( birthdate[ : dot1 ] ) my_month = int( birthdate[ dot1 + 1 : dot2 ] ) my_year = int( birthdate[ dot2 + 1 : ] ) print("Today is ",d,".",m,".",y) print("Your date of birth is ",my_day,".",my_month,".",my_year) age = today_year - my_year if my_month > today_month: age = age - 1 elif my_month == today_month and my_day > today_day: age = age - 1 print("You are ",age," years old")
- Question: can you work out what rindex() is doing?
- Notice I’ve used commas to join these items together in the print() command? This is a special feature of print that allows us to mix text strings and numbers without having to use str() for every number. It really only works for print… you are probably better off practicing use of str() instead!