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

Your turn:

Test this if/elif/else loop with other values of x to make sure that it works as expected.

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? (try to come up with a hypothesis before running it).

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

Now, what about?

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

Multiple iterables

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

Your turn:

Strings can be concatenated with the + sign in Python.

Example:

print("This is" + " a test.")
This is a test.

Now, consider the 2 variables:

names = ["Paul", "Eric", "Lucie"]
desserts = ["ice cream", "cakes", "pies"]

Create a loop that will print:

Paul likes ice cream
Eric likes cakes
Lucie likes pies

Nested loops

Loops can be nested. To understand how nested loops work, look at the following exercise.

Your turn:

What is the difference between the following 2 snippets of code:

for i, j in zip(['A', 'B', 'C'], ['a', 'b', 'c']):
    print(i + j)
Aa
Bb
Cc

and

for i in ['A', 'B', 'C']:
    for j in ['a', 'b', 'c']:
        print(i + j)
Aa
Ab
Ac
Ba
Bb
Bc
Ca
Cb
Cc

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

Your turn:

What is the problem with the following loop (DON’T RUN IT IN JUPYTER):

i = 10
while i >= 0:
    print(i)
    i += 1