# Flow control¶

## Boolean operators¶

Boolean operators are operators which compare values. Unlike mathematical operators, such comparisons do not return a number, but a value representing either 'TRUE' or 'FALSE'. Such a value is called a Boolean value. The following Boolean operators can be used in combination with numerical values:

 Operator Description == egual to > greater than < less than >= greater than or equal to <= less than or equal to

When operands are combined with Boolean operators, this combination is referred to as an expression. An expression is not yet a statement in itself, however. It is not an independent instruction for the computer. Boolean expressions are commonly used in statements which determine the flow control.

## Selection¶

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. Alternatively, statements may also need to be repeated as long as a certain condition applies.

In Python, there are various keywords that you can use to specify if, or how many times, a statement needs to be executed. These keywords are referred to as flow control structures. They typically make use of a Boolean expression which, in a given situation, can either be true or false.

If a certain section of your program must only be executed if a certain condition is true, you can use the keyword ‘if’. When the expression following ‘if’ is true, the statements underneath the expression are executed. If not, these statements are ignored. The listing below offers an example:

In [ ]:
number = 25

if number > 20:
print("The number is higher than 20!")


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 using four spaces. In most code editors, the indentation that is created when you hit the tab button has exactly the length of four spaces. 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, however, 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.

In [ ]:
time = 22

if time < 12:
print('Good morning!')
elif time < 18:
print('Good afternoon!')
else:
print('Good evening')


If the condition that follows the ‘if’ keyword can be evaluated as 'true', the first code block will be executed. 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 will be executed only if all the two earlier conditions are evaluated to 'false'.

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.

# Intermezzo: the format() function¶

As was discussed above, you can use the print() function to communicate the output of your programme. About this function, it is important to stress that it can only take sting variables as input. In some situations, however, your output may consist of a combination of strings and other types of variables. This can be the case when you want to print a longer sentence discussing the results of a calculation, such as “5 plus 7 is 12”. If this is the sentence that you want to print, the integers in this sentence need to be converted into strings first, via the str() function. It may be accomplished as follows:

In [ ]:
a = 5
b = 7

print( str(a) + ' plus ' + str(b) + ' is ' + str( a+b ) )

## This prints '5 plus 7 is 12'


Having to convert all integers to strings may be slightly cumbersome. An alternative solution is to make use of the format() method. It is a method which can convert any type of variable into a string. To use it, you need to append the name of the method to the string that you want to print. Within the parentheses, you need to mention all the variables whose values you want to print. Additionally, the string that you want to print needs to contain so-called placeholders, on the locations where the values of these variables should appear. These placeholders take the form of an empty set of curly brackets. The number of placeholders needs to be exactly the same as the number of variables mentioned in the format function. The format() returns a formatted string, with all variables simply inserted into the string, on the locations indicated by the placeholders.

In [ ]:
a = 5
b = 7

print( '{} plus {} is {}'.format( a , b , a+b ) )

## This prints '5 plus 7 is 12'


# 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 are repeated by making use of ‘while’ or ‘for’. 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 expression is true. Clearly, it is necessary to ensure that the expression can also be evaluated to ‘false’ at some point, since the repetition will otherwise continue endlessly. The variable that can end the loop is called the iteration value.

The code below prints the multiplication table for the number 7. In the code below, the number of repetitions are counted using variable named i. The value of this variable is incremented in each repetition. The loop will terminate after the variable i has reached the value 11.

In [ ]:
number = 7

i = 1

while i <= 10:
print("{} times {} is {}.".format(i,number,(i*number)))
i += 1


The same algorithm can be implemented using the ‘for’ keyword. This keyword can be used in combination with the range() function, for instance, which can be used to generate a list of numbers. When the function is used with two integers, the function starts the list with the number which is mentioned first and it continues to add integers, 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. The line ‘for i in range( 1 , 11 )’, in the code below, starts a sequence of 10 loops. The code block below the ‘for’ keyword will be repeaded 10 times.

In the code block underneath the line starting with 'for', the variable 'i' is assigned a different value during each of these iterations. It will receive the value 1 during the first loop, 2 during the second loop, and so on, as long as the value of i is less than 11.

In [ ]:
number = 8
i = 1

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