4. 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 the two 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 4.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 hour

  • Assign 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 hour has value 10, for instance, the code should print 'Good morning!' and if hour has 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. With for, you can specify that block of code needs to be repeated for each item in this collection. Examples of such collections include lists and dictionaries, which will be discussed at a later point in this tutorial. Such a collection of values can also be created via the range() function, which can be used to generate a list of numbers. When this range() function is used with two integers, the function starts the list with the number which is mentioned first and it continues to add integers to the list, as long as the value of these numbers is less than the number which is mentioned secondly. When you use range(1,11), for instance, this results in a list of integers ranging from 1 up and until 10, but not including 11.

The code below prints the multiplication table for the number 7.

number = 7

for i in range(1,11):
    print( f"{ i } times { number } is { i*number }." )

The number of repetitions are counted using a variable named i. 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. The line for i in range(1,11) starts a sequence of 10 loops. In this example, the variable named i successively receives all the values generated by the range() function.

The same algorithm can be implemented using the while keyword. It carries out repetiutions using a slightly differnt 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 actucally be evaluated to False at some point. If this is not the case, the repetition will continue endlessly.

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 4.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 print all each characters of a string on a separate line.

text = 'Flow control'

Exercise 4.3.#

Define a list ranging from 1 to 100 using the range() function. Next, print the cumulative sum of all the numbers in this collection of numbers.

Exercise 4.4.#

Building on the code you developed for exercise 4.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

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 4.5.#

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.