x = 3
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:
In the simplest case, we have:
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:
Example:
We can make this even more complex with:
Example:
-3 is negative
Your turn:
Test this if/elif/else loop with other values of x to make sure that it works as expected.
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:
Example:
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).
Now, what about?
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:
Your turn:
Strings can be concatenated with the + sign in Python.
Example:
Now, consider the 2 variables:
Create a loop that will print:
Paul likes ice cream
Eric likes cakes
Lucie likes pies
Loops can be nested. To understand how nested loops work, look at the following exercise.
While loops run as long as a predicate remains true. They follow the syntax:
Example: