Conditional statements#

Attention

Finnish university students are encouraged to use the CSC Notebooks platform.
CSC badge

Others can follow the lesson and fill in their student notebooks using Binder.
Binder badge

In this lesson we will learn how to make choices in our code using conditional statements (if, elif, else) and Boolean values (True, False).

Sources#

This lesson is based on the Software Carpentry group’s lessons on Programming with Python and McKinney’s book (2017): Python for Data Analysis.

Basics of conditional statements#

Conditional statements can change the code behaviour based on certain conditions. The idea is simple: If a condition is met, then a set of actions are performed.

A simple conditional statement#

Let’s look at a simple example with temperatures, and check if the temperature 17 (celsius degrees) is hot or not.

temperature = 17

if temperature > 25:
    print(f"{temperature} is hot!")
else:
    print(f"{temperature} is not hot!")
17 is not hot!

What did we do here? First, we used the if and else statements to determine what parts of the code to execute.

What do these tests do? The if statement checks to see whether the variable value for temperature is greater than 25. If this condition were true, '17 is hot' would be written to the screen. Since 17 is smaller than 25, the if condition is false and thus the code beneath else is executed. Notice that the code indented under the if statement is not executed if the condition is not true. Instead, code under the else statement gets executed. The code under the else statement will run whenever the if condition is false.

Check your understanding#

Update the value of temperature to a “hot” temperature:

Hide code cell content
# Here's one possible solution
temperature = 30

if temperature > 25:
    print(f"{temperature} is hot!")
else:
    print(f"{temperature} is not hot!")
30 is hot!

if without else?

The combination of if and else is very common, but the else statement is not strictly required. Python simply does nothing if the if statement is False and there is no else statement.

Try it out yourself by typing in the previous example without the else statement:

temperature = 17

if temperature > 25:
    print(f"{temperature} is greater than 25")

Makes sense, right? Conditional statements always check if the conditional expression evaluates as True or False. If True, the code under the conditional statement gets executed.

In the case above, nothing is printed to the screen if temperature is less than or equal to 25.

Another example from our daily lives#

As it turns out, we all use logic similar to if and else conditional statements daily. Imagine you’re getting ready to leave your house for the day and want to decide what to wear. You might look outside to check the weather conditions. If it is raining, you will wear a rain jacket. Otherwise, you will not. In Python we could say:

weather = "rain"

if weather == "rain":
    print("Wear a raincoat!")
else:
    print("No raincoat needed.")
Wear a raincoat!

Note here that we use the == operator to test if a value is exactly equal to another.

Note the syntax

Similar to for loops, Python uses colons (:) and whitespace (indentations) to structure conditional statements. If the condition is True, the indented code block after the colon (:) is executed. The code block may contain several lines of code, but they all must be indented identically. You will receive an IndentationError, a SyntaxError, or unwanted behavior if you haven’t indented your code correctly.

Check your understanding#

We might also need some other rainwear on a rainy day. Let’s add another instruction after the weather == rain condition so that the code would tell us to:

Wear a raincoat
Wear rain boots
Hide code cell content
# Here's one possible solution
weather = "rain"

if weather == "rain":
    print("Wear a raincoat")
    print("Wear rain boots")
else:
    print("No rainwear needed")
Wear a raincoat
Wear rain boots

Comparison operators#

Comparison operators such as > and == compare the values on each side of the operator. Here is the full list of operators used for value comparisons in Python:

Operator

Description

<

Less than

<=

Less than or equal to

==

Equal to

>=

Greater than or equal to

>

Greater than

!=

Not equal to

Boolean values#

Comparison operations yield boolean values (True or False). In Python, the words True and False are reserved for these Boolean values, and can’t be used for anything else.

Let’s check the current value of the conditions we used in the previous examples:

temperature > 25
False
weather == "rain"
True

if, elif and else#

We can link several conditions together using the “else if” statement elif. Python checks the elif and else statements only if previous conditions were False. You can have multiple elif statements to check for additional conditions.

Let’s create a chain of if, elif, and else statements that are able to tell us whether the temperature is above freezing, exactly at the freezing point, or below freezing.

temperature = -3
if temperature > 0:
    print(f"{temperature} degrees celsius is above freezing")
elif temperature == 0:
    print(f"{temperature} degrees celsius is at the freezing point")
else:
    print(f"{temperature} degrees celsius is below freezing")
-3 degrees celsius is below freezing

Check your understanding#

Let’s assume that yesterday it was 14°C, it is 10°C outside today, and tomorrow it will be 13°C. The following code compares these temperatures and prints something to the screen based on the comparison.

yesterday = 14
today = 10
tomorrow = 13

if yesterday <= today:
    print("A")
elif today != tomorrow:
    print("B")
elif yesterday > tomorrow:
    print("C")
elif today == today:
    print("D")

Which of the letters A, B, C, and D would be printed to the screen? Select your answer from the poll options at https://geo-python.github.io/poll/.

Hide code cell content
# Here is the solution
yesterday = 14
today = 10
tomorrow = 13

if yesterday <= today:
    print("A")
elif today != tomorrow:
    print("B")
elif yesterday > tomorrow:
    print("C")
elif today == today:
    print("D")
B

Combining conditions#

We can also use and and or to combine multiple conditions using boolean values.

Keyword

Example

Description

and

a and b

True if both a and b are True

or

a or b

True if either a or b is True

if (1 > 0) and (-1 > 0):
    print("Both parts are true")
else:
    print("At least one part is not true")
At least one part is not true
if (1 < 0) or (-1 < 0):
    print("At least one test is true")
At least one test is true

Note the syntax

Later in the course we will also use the bitwise operators & for and, and | for or.

Check your understanding#

Let’s return to our example about making decisions on a rainy day. Imagine that we consider not only the rain, but also the wind speed. If it is windy or raining, we’ll just stay at home. If it’s not windy or raining, we can go out and enjoy the weather!

8 m/s is the limit for a “fresh breeze” (navakka tuuli in Finnish) and we can set that as our comfort limit in the conditional statement. In this example, let’s imagine the Finnish Meteorological Institute has forecast strong winds in Helsinki (https://en.ilmatieteenlaitos.fi/local-weather/helsinki). Let’s see what our Python program tells us to do.

Hide code cell content
# Here is a solution
weather = "rain"
wind_speed = 9

# If it is windy or raining, print "stay at home", else print "go out and enjoy the weather!"
if (weather == "rain") or (wind_speed >= 8):
    print("Just stay at home")
else:
    print("Go out and enjoy the weather! :)")
Just stay at home

As you can see, we better just stay home if it is windy or raining (or both)! If you don’t agree, you can modify the conditions and print statements accordingly.

Combining for-loops and conditional statements#

Finally, we can also combine for-loops and conditional statements. Let’s iterate over a list of temperatures, and check whether the temperature is hot or not.

temperatures = [0, 28, 12, 17, 30]

# For each temperature, if the temperature is greater than 25, print "..is hot"
for temperature in temperatures:
    if temperature > 25:
        print(f"{temperature} is hot")
    else:
        print(f"{temperature} is not hot")
0 is not hot
28 is hot
12 is not hot
17 is not hot
30 is hot