= 3
x if x >= 0:
print(x, 'is positive')
3 is positive
Marie-Hélène Burle
Control flow statements alter the linear execution of code, allowing for one or another section of code to be executed, or for one section of code to be executed multiple times.
Conditionals dictate the flow of information based on predicates (statements that return True
or False
).
Example predicates:
4 < 3
2 == 4
2 != 4
2 in range(5)
2 not in range(5)
3 <= 4 and 4 > 5
3 <= 4 and 4 > 5 and 3 != 2
3 <= 4 or 4 > 5
In the simplest case, we have:
if <predicate>:
<some action>
This translates to:
<predicate>
evaluates to True
, the body of the if statement gets evaluated (<some action>
is run),<predicate>
evaluates to False
, nothing happens.Examples:
Nothing gets returned since the predicate returned False
.
Let’s add an else
statement so that our code also returns something when the predicate evaluates to False
:
if <predicate>:
<some action>
else:
<some other action>
Example:
We can make this even more complex with:
if <predicate1>:
<some action>
elif <predicate2>:
<some other action>
else:
<yet some other action>
Example:
For loops run a set of instructions for each element of an iterable.
An iterable is any Python object cable of returning the items it contains one at a time.
Examples of iterables:
For loops follow the syntax:
for <iterable>:
<some action>
Example:
Your turn:
Remember that the indentation matters in Python.
What do you think that this will print?
Strings are iterables too, so this works:
To iterate over multiple iterables at the same time, a convenient option is to use the function zip
which creates an iterator of tuples:
While loops run as long as a predicate remains true. They follow the syntax:
while <predicate>:
<some action>
Example: