This page was generated from source/notebooks/L3/conditional-statements.ipynb.
Binder badge
Binder badge CSC badge

Conditional statements

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 is performed.

A simple conditional statement

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

[1]:
temperature = 17

if temperature > 25:
    print('it is hot')
else:
    print('it is not hot')
it 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 is met, 'it is hot' would be written to the screen. Since 17 is smaller than 25, the code beneath else is executed. Code under the else statement will run whenever the if test is False.

Let’s look at 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 home 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:

[2]:
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

Similarly as with for-loops, Python uses colons (:) and whitespace (indentations; often four spaces) 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:

weather = 'rain'

if weather == 'rain':
    print('Wear a raincoat')
    print('Wear rain boots')
    print('Bring an umbrella')
else:
    print('No rainwear needed')

You will receive an IndentationError, a SyntaxError, or unwated behavior if you haven’t indented the code correctly.

Try changing the indentation in the above examples and see what output or errors you get:

[ ]:

Comparison operators and boolean values

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

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:

[3]:
temperature > 25
[3]:
False
[4]:
weather == 'Rain'
[4]:
False

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

if without else?

The combination of if and else is very common, but the else-statement is not strictly required.

temperature = 17

if temperature > 25:
    print(temperature,'is greater than 25')

Python simply does nothing if the if-statement is False and there is no else-statement.

Try it out yourself:

[5]:
temperature = 17
[6]:
if temperature > 25:
    print(temperature,'is greater than 25')

Nothing is printed to the screen if temperature is smaller than 25.

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 if the temperature is above freezing, exactly at freezing point or below freezing:

[7]:
temperature = -3
[8]:
if temperature > 0:
     print(temperature, 'is above freezing')
elif temperature == 0:
     print(temperature, 'is freezing')
else:
     print(temperature, 'is below freezing')
-3 is below freezing

Attention, poll pause!

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/.

Combining conditions

We can also use and and or to combine multiple conditions on 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
[9]:
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
[10]:
if (1 < 0) or (-1 < 0):
    print('At least one test is true')
At least one test is true

How about two False values? Try out what happens if you connect two False expressions using the and keyword:

[ ]:

Note: later on we will also need the bitwise operators & for and, and | for or.

Let’s return to our example about making decisions on a rainy day ☔. Imagine that we consider not only the rain, but also whether or not it is windy. 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! Let’s try to solve this problem using Python:

[11]:
weather = 'rain'
wind = 'windy'

if (weather == 'rain') or (wind == 'windy'):
    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 😏. 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 if the temperature is hot or not:

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

for temperature in temperatures:
    if temperature > 25:
        print(temperature, 'celsius degrees is hot')
    else:
        print(temperature, 'is not hot')
0 is not hot
12 is not hot
17 is not hot
28 celsius degrees is hot
30 celsius degrees is hot