Making decisions using “if”

We get Python to make decisions about what code to run on the basis of the True or 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.

Try this:

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:

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

Important notes:

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.


Multiple “elif”s

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")

If/else exercises

  1. 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
  2. Given an integer, print “odd” if it’s odd and print “even” otherwise. For example, given 5, print odd.

  3. Given two integers, print the least of them. For example, given inputs of 3 and 7, print 3.

  4. Given an integer, print “YES” if it’s a three-digit number and print “NO” otherwise. For example, input of 179 should output YES, while input of 13 or A = 1234 should output NO.

  5. Given a three-digit integer X consisting of three different digits, print “YES” if its three digits are going in an ascending order from left to right and print “NO” otherwise. For example, input of 179 should output YES and input of 197 should output NO.

  6. An extension of question 2. Given 3 integers, print the least of them.

  7. Given a month - an integer from 1 to 12, print the number of days in it (assume not a leap year). For example, input of 1 should output 31.

  8. Given the year number. You need to check if this year is a leap year. If it is, print LEAP, otherwise print COMMON.

    The rules in Gregorian calendar are as follows:

    • a year is a leap year if its number is exactly divisible by 4 and is not exactly divisible by 100;
    • but a year is always a leap year if its number is exactly divisible by 400. For example input of 2012 should output LEAP.
  9. Combine exercise 6 and 7 so that your days in a month calculation is able to correctly determine whether or not it is a leap year, and will output accordingly.

  10. Given three integers, print them in ascending order. For example, given the inputs of 5, 3 and 7, output 3 5 7.

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.


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")