Conditional if

Conditional if statements allow programs to make decisions and execute different code based on whether certain conditions are True or False. For instance, we may want to perform a different action when a study participant is an adult or not:

IF (participant_age >= 18)
    DO SOMETHING
OTHERWISE
    DO SOMETHING ELSE

The basic syntax for conditional statements is if condition:, where condition is an expression that evaluates to either True or False, i.e. a boolean. If it’s True, the indented code block under the if statement will run. If False, it will be skipped. For example, the below code will print “You are an adult” if age is 18 or higher.

age = 18
if age >= 18:
    print("You are an adult")
You are an adult

You can also add an else clause to specify code to run if the condition is False:

age = 17
if age >= 18:
    print("You are an adult")
else:
    print("You are not an adult")
You are not an adult

For multiple conditions, you can use elif (else if) clauses to execute the first matching block.

age = 14
if age < 13:
    print("You are a child") 
elif age < 18:
    print("You are a teenager")
else:
    print("You are an adult")
You are a teenager
if statement syntax
An if statement has scaffolding as well as user-supplied parts. The scafolding is the word if and the colon : as shown below.
 ↓                ↓
if my_number > 100:
    print(my_number, "is large")
The user-supplied part is the conditional:
          ↓
if my_number > 100:
    print(my_number, "is large")
As before, the body must be indented by four spaces:
if my_number > 100:
    print(my_number, "is large")
  ↑
indentation

You can chain multiple conditions with elif using the same syntax. On the contrary, else provides a default case if no conditions are True and do not requiere a condition.

Exercise

To explore the behaviour of the if statement, we could edit the below if.py script to change the value of my_number via an input function call. The input function will always return a string, even if you enter digits so we need to explicitly convert the input into an integer with the int function.

if.py
my_number = int(input("Enter a number: "))  # We can nest function calls directly

if my_number > 100:
    print(my_number, "is large")

Run the program with different inputs. Does it give you what you expect? What happens if the input is smaller than 100?

if.py
# We can nest function calls directly
my_number = int(input("Enter a number: "))  

if my_number > 100:
    print(my_number, "is large")

If my_number is smaller than 100 then the expression is false and so if does not trigger and nothing is printed:

Terminal/Command Prompt
python if.py
Enter a number:  42
Enter a number:  128
128 is large
Exercise 2

Experiment with editing if.py to use some different boolean statements. Make sure you remember to save the file after each change before running it.

Less than:

if.py
my_number = int(input("Enter a number: ")) 

if my_number < 100:
    print(my_number, "is less than 100")
Terminal/Command Prompt
python if.py
Enter a number:  74
74 is less than 100


Equal to:

if.py
my_number = int(input("Enter a number: "))  

if my_number == 100:
    print(my_number, "== 100")
if my_number == 74:
    print(my_number, "== 74")
Enter a number:  74
74 == 74


Not equal to:

if.py
my_number = int(input("Enter a number: ")) 

if my_number != 100:
    print(my_number, "!= 100")

if my_number != 74:
    print(my_number, "!= 74")
Enter a number:  74
74 != 100

Ordering your options

When working out which lines of code will be run, Python will work down the list of if, elifs and else and will run the first one that matches. Once it’s matched one, it will not bother checking to see if any of those later on would have matched. This means that you should order your questions from most-specific to least-specific.

For example, if you want to do one thing for positive numbers, but something special instead for numbers greater than 100, then you should put the more specific check first:

if.py
my_number = int(input("Enter a number: "))

if my_number > 100:
    print(my_number, "is large")
elif my_number > 1:
    print(my_number, "is positive")
else:
    print(my_number, "negative")
Exercise

Create a file leap_year.py which calculates, for a given year, whether it is a leap year and prints out the answer. You might want to read the year in using input, or you could hard-code it in the program.

The rules to follow are:

  1. if the year is divisible by 400 then it’s a leap year,
  2. otherwise, if the year is divisible by 100 then it’s not,
  3. otherwise, if the year is divisible by 4 then it’s a leap year,
  4. otherwise, it’s not.

To simplify the writing of the program, you might find it easier to start with the divisible-by-4 condition, then add in the divisible-by-100 check and then add in the divisible-by-400 calculation.

For reference, here are some years for you to check against:

  • 2023 - not a leap year as it’s not divisible by 4
  • 2024 - a leap year as it’s divisible by 4 (and not by 100)
  • 1900 - not a leap year as it’s divisible by 100 (and not by 400)
  • 2000 - a leap year as it’s divisible by 400

Whenever solving a problem like this, it’s always good to build it up one step at a time. You could be tempted to jump right to the solution but it is easier to take small steps and check your results along the way than debugging a long piece of code.

Divisible by 4

The first step is to implement the simplest of the logical checks: is the year divisible by \(4\)? If it is, print out an appropriate message:

leap_year.py
year = int(input("Enter a year: "))

if year % 4 == 0:
    print(year, "is a leap year")

and check that it works for a know leap year.

Terminal/Command Prompt
python leap_year.py
Enter a year: 2024
2024 is a leap year

For a year that we know is not a leap year, what do we get:

Enter a year: 2023

We get no output, so let’s fix that next, by adding an else:

leap_year.py
year = int(input("Enter a year: "))

if year % 4 == 0:
    print(year, "is a leap year")
else:
    print(year, "is not a leap year")
Enter a year: 2023
2023 is not a leap year

So far it’s looking like it’s doing the right thing. We have a working leap year calculator which covers most cases correctly.

Divisible by 100

Let’s check the next corner case: what happens if the year is divisible by 100. The rules say that this should not be a leap year:

Enter a year: 1900
1900 is a leap year

So it’s currently getting this wrong. We need to add in a check to see if the year is divisible by 100 and set it to be labelled as not a leap year.

Here we need to be careful as any number which is divisible by 100 is also divisible by 4 but we want a special thing to happen in the former case. The divisible-by-100 check is more specific than the divisible-by\(4\) check, so it must come first in the if-elif-else chain:

leap_year.py
year = int(input("Enter a year: "))

if year % 100 == 0:
    print(year, "is not a leap year")
elif year % 4 == 0:
    print(year, "is a leap year")
else:
    print(year, "is not a leap year")
Enter a year: 2024
2024 is a leap year
Enter a year: 2023
2023 is not a leap year
Enter a year: 1900
1900 is not a leap year

Divisible by 400

The code is working for all those cases correctly, however, the last condition to think about is what happens for the year 2000:

Enter a year: 2000
2000 is not a leap year

This year should be a leap year as it is divisible by 400. Again this is more specific than the previous two so must be added before them in the chain:

leap_year.py
year = int(input("Enter a year: "))

if year % 400 == 0:
    print(year, "is a leap year")
elif year % 100 == 0:
    print(year, "is not a leap year")
elif year % 4 == 0:
    print(year, "is a leap year")
else:
    print(year, "is not a leap year")
Enter a year: 2024
2024 is a leap year
Enter a year: 2023
2023 is not a leap year
Enter a year: 1900
1900 is not a leap year
Enter a year: 2000
2000 is a leap year

Combining questions

It is possible to ask two or more questions in one go by combining them with and and or. So, if you want to check is a number is smaller than ten (my_number < 10) and is not equal to zero (my_number != 0), you can use:

if my_number < 10 and my_number != 0:
    ...

These combined checks can be used is both if and elif statements.

Exercise

Could you figure out how to rewrite leap_year.py with a single if-else statement?

leap_year.py
year = int(input("Enter a year: "))

if ( (not(year % 100 == 0) and (year % 4 == 0)) or (year % 400 == 0) ) :
    print(year, "is a leap year")
else:
    print(year, "is not a leap year")
Enter a year: 2024
2024 is a leap year
Enter a year: 2023
2023 is not a leap year
Enter a year: 1900
1900 is not a leap year
Enter a year: 2000
2000 is a leap year