Python challenge: Controlling the flow
This post presents some basic commands for control flow, specifcally if
-statements, while
and for
-loops
If
-statements
Let’s start with a simple if statement:
Important to note here are two things: The if-clause ends with a colon and the body of the if-statement needs to be indented correctly.
An if-statement can be combined with an else
-clause in the following way:
Again, the body belonging to the else branch needs to be indented.
The ternary operator is an alternative for if
..else
:
.
Another variant is if
..elif
which allows to handle multiple branches in the flow of our code:
while
-loops
Following is a simple example of a while
-loop
for
-loops
for
-loops can be used in various ways, e.g. for iterating through a string:
The limit of the loop can be defined using the range
keyword:
It is also possible to define the counting interval:
Last but not least, a for
-loop can be executed backwards: