2  Control Flow Statements

What does the title of this chapter even mean? Well, it’s a fancy way of saying that we can control which parts of our program code will get executed. We can make decisions based on variable values, we can repeat actions, and we can do all sorts of things that make our programs more interesting and useful. Let’s start with the most basic control flow statement: the if statement.

2.1 The if statement

The if statement evaluates a condition and based on it’s value (True or False) it will execute or skip a block of code.

if True:
    print('This will be printed')

if False:
    print('This will not be printed')
This will be printed

We are not limited to using boolean values in the condition. We can use any expression that evaluates to a boolean value.

name = 'Tero'

if name == 'Tero':
    # code block to be executed if the condition is True
    print('Hello Tero!')
Hello Tero!

You should note that unlike some other programming languages, Python does not use curly braces to define code blocks. Instead, Python uses indentation. The code block should be indented with 4 spaces. Most (all?) modern code editors should handle this automatically, so you needn’t worry about it too much.

2.1.1 Extending the if statement with elif and else

What if we want to execute some code also if the condition is False? We can use the else statement for that.

name = 'Antero'

if name == 'Tero':
    print('Hello Tero!')
else:
    print('Hello stranger!')
Hello stranger!

And in the case of multiple conditions, we can use the elif statement to check for additional conditions if the previous conditions were False.

name = 'Antero'

if name == 'Tero':
    print('Hello Tero!')
elif name == 'Antero':
    print("Oh, it's you again!")
else:
    print('Hello stranger!')
Oh, it's you again!

That is the basic idea behind the if-else statement. You can have as many elif statements as you want, but only one (or none) else statement which is located at the end. Conditions can also be nested.

name = 'Tero'
age = 30

if name == 'Tero':
    if age < 18:
        print('Hello young Tero!')
    else:
        print('Hello adult Tero!')
else:
    print('Hello stranger!')
Hello adult Tero!

2.2 The for loop

The idea behind a loop structure is to repeat a block of code multiple times. The for loop is used when we know how many times we want to repeat the code block.

seasons = ['Spring', 'Summer', 'Autumn', 'Winter']

for season in seasons:
    print('It is now {}'.format(season))
It is now Spring
It is now Summer
It is now Autumn
It is now Winter

The for loop iterates over the elements of the seasons list. In each iteration, the variable season is assigned the value of the current element. The loop continues until all elements have been iterated over. This is useful for example when we need to repeat a calculation several times.

squared_numbers = []

for i in range(1, 6):
    squared_numbers.append(i**2)

print(squared_numbers)
[1, 4, 9, 16, 25]

2.3 The while loop

The while loop is the for loop’s liberal cousin. It is less restrictive and repeats a block of code as long as a condition is True. Depending on the condition we might not know how many times the loop will be executed beforehand. The price for this freedom is that we might accidentally create an infinite loop if we’re not careful. Let’s look at a simple example, which demonstrates the basic idea.

count = 0

while count < 5:
    print('Count is {}'.format(count))
    count += 1
Count is 0
Count is 1
Count is 2
Count is 3
Count is 4

The example above could have been implemented with a for loop as well. As a rule of thumb a forloop can always be written as a while loop, but not the other way around. We can also use the break statement to exit the loop.

start = 0
end = 5

while True:
    print(f'Count is {start}')
    start += 1
    if start >= end:
        break
Count is 0
Count is 1
Count is 2
Count is 3
Count is 4

2.4 Conclusion

In this chapter we learned about the basic control flow statements in Python. We can use the if statement to make decisions based on conditions, the for loop to repeat a block of code a known number of times, and the while loop to repeat a block of code as long as a condition is True. In the next chapter we will learn about functions, which are a way to organize our code and make it more reusable.