Conditions#

The if statement (a control flow tool), followed by an expression, can be used to execute code conditionally.

That means only if that expression evaluates to True. For such expressions, logical operators from mathematics can be used.

See also:

Let’s take a look at some expressions first:

a = 3
b = 4
# equal
a == b
False
# not equal
a != b
True
# greater
a > b
False
# less
a < b
True
# greater equal
a >= b
False
# less equal
a <= b
True

The if statement#

After using if in combination with an expression, you need to put a colon :. The following code for execution must be indented:

if 3 < 4:
    print("Math is great.")
Math is great.
if 3 > 4:
    print("Math is broken.")

You can also write more sophisticated expressions using and and or:

c = 10

if (c > 4) and (c < 20):
    print("C is between 4 and 20.")
C is between 4 and 20.

If you want to check if an element is in an array, do it like this:

animals = ['cat', 'dog', 'mouse']

if 'cat' in animals:
    print('Our list of animals contains a cat')
Our list of animals contains a cat

You can also analyse strings. For example, check if they start or end with certain characters:

filename = "cells.tif"

if filename.endswith("tif"):
    print("The file is an image!")
The file is an image!

The if-else statement#

If you have two different blocks of code that should be executed alternatively, use if-else:

quality_in_percent = 89

if quality_in_percent > 90:    
    print("Our quality is high enough.")
else:
    print("We need to improve our quality.")
We need to improve our quality.

The elif statement#

For executing code depending on multiple conditions, use the elif-statement:

quality_in_percent = 100

if quality_in_percent > 90:    
    print("Our quality is high enough.")
elif quality_in_percent > 60:
    print("Our quality is medium.")
else:
    print("We need to improve our quality.")
Our quality is high enough.

Exercise#

Write python code that prints out the daytime, e.g. “morning”, “noon”, “afternoon”, “evening”, and “night” depending on a given time.

# it's 12:15
time_hours = 12
time_minutes = 15