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 is 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 weird.")
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:
# determining the exam grade depending on
number_of_correct_points = 23
number_of_total_points = 30
# compute percentage
percentage = number_of_correct_points / number_of_total_points * 100
if percentage > 95:
grade = 1
elif percentage > 80:
grade = 2
elif percentage > 60:
grade = 3
elif percentag > 50:
grade = 4
else:
grade = 5
print("You scored", number_of_correct_points, "out of", number_of_total_points)
print("Your grade is", grade)
You scored 23 out of 30
Your grade is 3
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