5. Flow control#
By default, Python moves through the code in a linear way. It simply executes all the statements in the order in which they are found in the programme. In some cases, however, a statement only needs to be performed under a certain condition. In other situations, statements may need to be repeated as long as a certain condition applies.
Flow control is the process of determining how often, or under which circumstances, a certain set of statement needs to be executed. In Python, there are various keywords that you can use to specify if, or how many times, a statement needs to be run.
Conditional execution#
To make sure that a certain section of your program is executed only if a certain condition is true, you can use the keyword if. This keyword is followed by a Boolean expression. This Boolean expression, in turn, is followed by a colon (’:’). When the expression following if is indeed true, the statements underneath the expression are executed. If not, these statements are ignored. The listing below offers an example:
grade = 7.5
print( f"Your grade is {grade}" )
if grade > 5.5:
print("This grade is sufficient!")
Importantly, the spatial layout of the code is not arbitrary. The block of code that must be executed when the condition is true is indented. In Python, such indents consist of four spaces. In most code editors, this indentation is added automatically when you hit the enter button after the colon following a Boolean expression. The statements that have the same indentation are all assumed to belong to the same block of code.
The exampe that was given only contains one condition. It is also possible to let Python evaluate a series of conditions. In this case, you need to use the keywords if, elif and else. An example can be seen below.
grade = 7.5
if grade > 9:
label = 'outstanding'
elif grade > 8:
label = 'very good'
elif grade > 7:
label = 'good'
elif grade > 6:
label = 'satisfactory'
else:
label = 'insufficient'
print( f'The grade is {grade} ({label})' )
Python moves across all the options in the order that is given. Each condition is evaluated in turn. If the condition that follows the if keyword can be evaluated as True, the first code block will be caried out. If not, the condition that is given after elif will be evaluated. Python will execute the second block of code if that second condition is found to be True. The final set of statements (i.e. those given after else) will be executed only if all of the earlier conditions are evaluated as False. This final code block may be viewed as the default option or the “catch all” option.
Note that only the keywords if and elif can be followed by a condition. The keyword else always appears WITHOUT such a condition. The code block given after else contains the actions that must be performed if all the earlier conditions are false.
Importantly, the lines starting with if, elif and else all end in a colon.
Exercise 5.1.#
Write some code which can print a text to welcome its users with messages such as ‘Good morning’, ‘Good afternoon’, or ‘Good evening’. The message that is printed should vary along with the time of the day.
Follow the steps below:
Create a variable named
hourAssign it a value in between 0 and 23.
Assuming that this variable represents a given time, print a message that is appropriate for the part of the day this hour is in. If the variable
hourhas value 10, for instance, the code should print'Good morning!'and ifhourhas value 23, the code should print'Good night!'
Iteration#
Next to the flow structures for selection, there are also flow control structures that can be used for repetitions of statements. Such repetitions are generally referred to as iterations. In Python, you can specify the number of times a set of statements need to be repeated by making use of for or while.
for, firstly, is used in combination with a collection of values, such as a list. With for, you can specify, for example, that a block of code needs to be repeated for each item in a list. This process of moving through all the elements in a list is also referred to as iterating over a list or navigating a list. for always needs to be used in combination with in. After in, you give the name of the list whose elements you want to retrieve. After for, you supply the name of a new variable that you can use to refer to each element in the list in sequence. This variable is referred to as the loop variable. You are free to name this variable as you wish, but bear in mind that you cannot choose reserved words. As always, it is best to choose a variable name that is meaningful in the context of the code. This loop variable gets assigned and reassigned during each cycle of the iteration.
In the example below, we print the names of the days in the week. We assign the current element to a new variable named day. During each cycle, the value of the variable day will be different; it will consecutively be assigned the various elements in the list named week. The loop will continue as long as there are items in the list.
week = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday","Saturday","Sunday"]
for day in week:
print( day )
Blocks of code can also be repeated using the while keyword. It carries out repetitions using a slightly different logic. As is the case for if, the while keyword should be followed by a test, or, more precisely, by a Boolean expression. The while keyword initiates a loop. The statements that follow while will be repeated as long as the Boolean expression is True, and the repetion ends as soon as the expression is found to be False. Clearly, it is necessary to ensure that the code block that is repeated can actually change the value of this Boolean expression, and that the expression can actually be evaluated to False at some point. If this is not the case, the repetition will continue endlessly.
The code below prints the multiplication table for the number 7.
number = 7
i = 1
while i <= 10:
print( f"{ i } times { number } is { i*number }." )
i += 1
In this second multiplication table, we explicitly need to increment the value of variable i using the += operator. The loop will terminate after the variable i has reached the value 10.
Remember that the code blocks that follow lines starting with if, elif, else, for and while all need to be indented.
Exercise 5.2.#
Strings can be viewed as collections of characters. When you iterate across a string using a for loop, you will receive each individual character in sequence. Try to write code which prints each character of the string on a separate line.
text = 'Flow control'
Exercise 5.3.#
The list named years brings together a number of years. Use the keywords for and if to select the years from this list that are in the 18th century. Remember that you can combine multiple Boolean expressions using and.
years = [ 1756, 1575, 2002, 1984 ,1626 ,1791, 1714, 1873, 1991 ]
# Print years that are in the 18th century
Exercise 5.4.#
Building on the code you developed for exercise 5.2, try to write code which can reverse the order of the characters in a given string.
You can test your code with the following examples:
Input |
Output |
|---|---|
time |
emit |
drawer |
reward |
stressed |
desserts |
Start by defining an empty output string, as follows.
output_string = ''
Next, iterate across all the individual characters of the string and append the output string to the right of this character.
Exercise 5.5.#
We have two lists of numbers and would like to know which numbers in the first list are not in the second list. Write code which can extract those numbers from the first list that are not in the second list.
first = [4, 9, 1, 17, 11, 26, 28, 54, 63]
second = [8, 9, 74, 21, 45, 11, 63, 28, 26]
numbers_not_in_second = []
# Add the numbers from `first` that are not in `second` to `numbers_not_in_second`
print(numbers_not_in_second)
Exercise 5.6.#
We have a list of websites and are interested to find the Dutch ones.
Write some code to select the Dutch websites from this list. Tip: You may want to reuse some of the code developed for exercise 3.4.
websites = [
'https://www.universiteitleiden.nl',
'https://www.stanford.edu',
'https://www.uu.nl',
'http://www.ox.ac.uk',
'https://www.rug.nl',
'https://www.hu-berlin.de',
'https://www.uva.nl'
]
# Print the URLs that belong to Dutch institutions
Aside: getting user input#
In the examples above, we first manually assigned a number (e.g., number = 8), and this number was then used in the rest of the code block. If we want to run the code with different input, we need to change our code. There is a way to ask for a value when the program is run (i.e. at runtime), namely, by using the input() function.
The input() function takes a string. This is generally a question or a prompt for a value. It returns the value that the user entered as a string.
name = input("What is your name?")
print(f"Hello, {name}!")
If you ask for a number using input("Please enter a number"), the value returned by input is still a string.
You can convert this value to an integer using the int(value) function.
If the string cannot be converted, for example if it is not actually a number, Python will raise an error.
my_number = input("Please enter a number: ")
print("The type of my_number is", type(my_number))
my_int = int(my_number)
print("The type of my_int is", type(my_int))
Exercise 5.7.#
Program a small guessing game. In this game, the player needs to guess a number in between 1 and 50. You can use the code below as a basis.
The randint() method from random can be used, firstly, to generate a random integer.
Use the function input() to request a value from the user. The function int() needs to be used to convert the input into an integer.
When the user enters a value which is too low or too high, this information is communicated to the user via a print statement. To test whether the number that is guesses is correct, you can work with the equality (==) and the inequality (!=) operators.
Hint: you will need to combine the different kinds of flow control to complete the whole game. Start by checking if the guessed number is correct and making sure that this part of the code works as you expect. When that works, think which parts of the code need to be repeated to let the player guess until the number was found.
from random import randint
# Generate our random number
number_to_guess = randint(1, 50)
# Ask the user to guess a number (see Ex. 4.3. for how to do this)
guessed_number =
# Check if this guess matches the number to guess
# If it doesn't, let the user guess again until they find the correct number.