Conditionals
Based on a given condition, decide which actions are to be taken.
Use case¶
Handle diverging paths of action based on the current state of the program.
Conditions
Conditions are expressed as statements that can be evaluated to be either True
or False
.
For example x > 5
, "H" in "Hello World"
, or isinstance(5, int)
Conditionals are made up of three main components, called branches. If any of these branches has a condition that is met, the code belonging to the branch will be run. Code that belongs to a branch is identified by directly following the conditional and being indented one level (4 spaces) relative to the conditional.
There can only be one
The conditions of the branches are checked in the order they appear. The first branch that will be chosen, completes the conditional. All other branches are then ignored. When writing a conditional, check the special cases first and the general ones later.
if
-branch¶
- Starts a new conditional
- Has a condition and will be taken if the condition is met
elif
-branch¶
- Optional, following an
if
or anotherelif
-branch - Has a condition and will be taken if the condition is met
else
-branch¶
- Optional, but always the last branch
- Has no condition and will always be taken if reached
- Used to specify the “last ressort”-cases
Example 1¶
A simple check if the condition x > 1000
is met.
Should this is the case, print the text x is a large number
Example 2¶
Check whether the term "Hello"
is contained in the variable my_text
.
Depending on whether this is the case, a text will be printed accordingly.
if "Hello" in my_text:
print("Your text contains the word \"Hello\"")
else:
print("Your text does not contain the word \"Hello\"")
Example 3¶
Check multiple conditions one after the other to decide on a course of action. Within each branch, arbitray complex code may be executed.
This example deals with the heat regulation of bath water.
We assume to have a heater and a cooler for the water and want to keep it in the range 25…35°C.
To control the devices we may have the set_heater_on(…)
and set_cooler_on(…)
to toggle these components on and off.
The variables heater_is_on
, cooler_is_on
and temperature
inform us about the state of our system.
if temperature > 35:
print("Water is too hot, will lower the temperature")
set_cooler_on(True)
elif temperature < 25:
print("Water is too cold, will raise temperature")
set_heater_on(True)
else:
print("Water temperature is acceptable for humans")
if heater_is_on:
set_heater_on(False)
if cooler_is_on:
set_cooler_on(False)
Note that the checks made in the else
-branch are independent of each other to guarantee that we check both, the heater and the cooler.
This is the reason why we use two if
statements instead of an if
… elif
combination.