Control flow

Author

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

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

If statements

In the simplest case, we have:

if <predicate>:
    <some action>

This translates to:

  • If <predicate> evaluates to True, the body of the if statement gets evaluated (<some action> is run),
  • If <predicate> evaluates to False, nothing happens.

Examples:

x = 3
if x >= 0:
    print(x, 'is positive')
3 is positive
x = -3
if x >= 0:
    print(x, 'is positive')

Nothing gets returned since the predicate returned False.

If else statements

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:

x = -3
if x >= 0:
    print(x, 'is positive')
else:
    print(x, 'is negative')
-3 is negative

If elif else

We can make this even more complex with:

if <predicate1>:
    <some action>
elif <predicate2>:
    <some other action>    
else:
    <yet some other action>

Example:

x = -3
if x > 0:
    print(x, 'is positive')
elif x < 0:
    print(x, 'is negative')
else:
    print(x, 'is zero')
-3 is negative

Loops

For loops

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:

range(5)
'a string is an iterable'
[2, 'word', 4.0]

For loops follow the syntax:

for <iterable>:
    <some action>

Example:

for i in range(5):
    print(i)
0
1
2
3
4

Your turn:

Remember that the indentation matters in Python.
What do you think that this will print?

for i in range(5):
    print(i)
print(i)

Strings are iterables too, so this works:

for i in 'a string is an iterable':
    print(i)
a
 
s
t
r
i
n
g
 
i
s
 
a
n
 
i
t
e
r
a
b
l
e

To iterate over multiple iterables at the same time, a convenient option is to use the function zip which creates an iterator of tuples:

for i, j in zip([1, 2, 3, 4], [3, 4, 5, 6]):
    print(i + j)
4
6
8
10

While loops

While loops run as long as a predicate remains true. They follow the syntax:

while <predicate>:
    <some action>

Example:

i = 0
while i <= 10:
    print(i)
    i += 1
0
1
2
3
4
5
6
7
8
9
10