John
Peter
Mark
Andrew
02. Control flow
Computational methods
Learning objectives
- Implement loops for repetitive tasks
- Understand common iterators in Python
- Use conditional statements to control program flow
- Apply list comprehensions for concise and efficient code
Control flow structures
Control flow structures allow directing the execution of a program based on a set of conditions, either iterative or conditional. These structures are foundational for decision making by either conditional criteria (e.g., threshold values), or by repeating calculations until a certain condition is met (e.g., time steps or iterating over a sequence).
Control flow structures are identified in Python with the colon notation :, followed by an indented block of instructions inside the control structure.
Iterative structures
Iterative structures repeat or loop through a set of instructions during a determined number of steps. The body of instructions is referred to as the loop body, while each repeating step is referred to as an iteration.
For statement
A for statement allow to execute a block of instructions for each value in a collection. Python offers several iterators to construct loops with a for statement, including a list, tuple or a dictionary. Note that a variable is declared inside the for statement, and it is used to loop over the values in the collection.
The variable declared in the for statement remains in memory once the loop is completed, and thus must be reassigned if a different value is later needed for the variable.
Common iterators
The range() function generates a memory efficient collection of integers to use in a for statement. This function returns a range iterator type that is open at the upper endpoint. If needed, a type cast to list can be used to unpack the sequence in the iterator:
range(0, 3) <class 'range'> 3
[0, 1, 2]
0
1
2
Most iterators are constructed using specific classes, so a type cast to a container class such as list or tuple is needed to unpack the sequence.
A range iterator can be used to access the values in a list by indexing:
0 John
1 Peter
2 Mark
3 Andrew
Another efficient way to iterate over a collection is the enumerate() function, which returns the index and value for each object in the collection. The function returns an enumerate iterator type, so a type cast to list can be used to unpack the sequence:
0 John
1 Peter
2 Mark
3 Andrew
<class 'enumerate'>
[(0, 'John'), (1, 'Peter'), (2, 'Mark'), (3, 'Andrew')]
In some instances we need to loop through several sequences in parallel. An efficient way to achieve the latter is to use the zip() function, which returns a tuple with the mapped values in each sequence. Similarly than before, the function returns a zip iterator type, so a type cast to tuple can be used to unpack the sequence:
John 32
Peter 35
Mark 28
Andrew 31
<class 'zip'>
(('John', 32), ('Peter', 35), ('Mark', 28), ('Andrew', 31))
We can also loop through the keys and values of a dictionary object with the method items(). The method returns a dict_items iterator type, so a type cast to list is used to unpack the sequence:
name John
age 32
<class 'dict_items'>
[('name', 'John'), ('age', 32)]
Additional classes for efficient iteration, including combinatorics, are implemented in the itertools library.
While statement
A while statement is a special type of iterative structure that executes a block of instructions while a given condition is True:
Counter: 0 (True)
Counter: 1 (True)
Counter: 2 (True)
Counter: 3 (True)
Counter: 4 (True)
Counter: 5 (False)
Note that the loop body needs to be updated manually, otherwise an infinite loop will occur!
Conditional structures
Conditional structures execute a set of instructions if a given condition is met. Python implement conditional structures through the if, else and elif statements.
If statement
An if statement executes a block of instructions if a given condition is True:
If else statement
An if statement can be followed by an optional else statement, which executes a block of instructions if the initial condition is False:
If elif statement
Alternatively, an if statement can be followed with one or more conditions that are verified sequentially through elif statements, which is an abbreviation of else if. This set of statements can be closed with an else statement, which is executed if all previous conditions are False:
Warm
if statements can also be constructed with logical conditions:
# variable assignment
a = -8 ; b = 2
# logical conditions
if (a > b) and (a - b >= 10):
print('a is much greater than b')
elif (b > a) and (b - a >= 10):
print('b is much greater than a')
elif (a > b):
print('a is greater than b')
elif (b > a):
print('b is greater than a')
else:
print('a is equal to b')b is much greater than a
Control flow commands
Control flow commands allow to modify the execution of block of instructions inside iterative structures:
break: ends the current loop.continue: proceeds with the next iteration.pass: position marker to avoid error when no action is required.
List comprehensions
Python offers list comprehension, which is a compact and efficient way to create lists based on a iterative control structure. The basic syntax is as follows: \[ [\text{instruction}\,for\,\text{item}\,in\,\text{iterator}] \]
[0, 1, 4, 9, 16, 25, 36, 49]
The variable declared in the for statement inside a list comprehension is local, so it doesn’t remain in memory –or affects a global variable with the same name– once the loop is completed.
List comprehension is very useful to create new lists based on a given operation in a previous list:
0 °C -> 32.0 °F
10 °C -> 50.0 °F
20 °C -> 68.0 °F
30 °C -> 86.0 °F
The iterative structure of a list comprehension also accepts conditional arguments, which can be used to filter an original sequence:
Even numbers: [0, 2, 4, 6]
Odd numbers : [1, 3, 5, 7]
A list comprehension also accepts nested iterations through multiple for statements:
Paired numbers : [(0, 1), (0, 3), (2, 1), (2, 3)]
Flattened pairs: [0, 1, 0, 3, 2, 1, 2, 3]
Exercises
- Declare the following variables:
- Use a
forloop to print each value innums. - Use a
forloop withenumerate()to print the index and value of each element intemps. - Use a
whileloop to print all values inrangethat are lower than 6. - Use a
forloop with acontinuestatement to print only the odd values innums. - Use a
forloop with abreakstatement to stop iteration when a temperature intempsexceeds 30, printing each index and value until the loop stops. - Construct a list
classifiedcontaining the label'even'or'odd'for each element innumsusing list comprehension with a conditional. - Compute the cumulative sum of
numsusing aforloop, storing each intermediate result in a listcumsum. - Write an
if/elif/elsestatement that classifies a temperature value as'Cold'(below 10),'Mild'(between 10 and 25), or'Hot'(above 25). - Use the code written in the previous exercise inside a
forloop to create a list with the temperature classification ('Cold','Mild', or'Hot') for each value intemps. - Use
zip()and list comprehension to create a list of tuples pairing each temperature intempswith its classification from the previous exercise.