Flow Control

conditional statements, loops, and functions

Any language has a way to control the flow of the program. This is primarily done by using conditional statements, loops, and functions. Flow control is the order in which the program executes statements - think of it like being directed by a traffic policeman on a busy road. The traffic policeman directs the traffic to move in a certain direction, stop, or go back. Similarly, flow control in programming directs the program to execute certain statements based on conditions, loop through a set of statements, or call a function.

Basic flow control

Let us start with the basic flow control statements in Python. Say that you want a program to execute a certain block of code only if a certain condition is met. This is where the if statement comes into play. The if statement is used to check a condition and execute a block of code only if the condition is True.

number = 4

if number % 2 == 0:
    print("Number is even")
Number is even

This example takes a number, and if it is divisible by two (the % operator is the modulo operator, which gives the remainder of the division of two numbers), it prints “Number is even”. What follows the if statement is called the “condition”, and it is a boolean expression that evaluates to either True or False. In fact you can print the evaluation of the condition alone to understand how this works:

print(number % 2 == 0)
True

But what if the number is not divisible by two? In that case, you can use the else statement to execute a block of code when the if condition is False.

number = 5

if number % 2 == 0:
    print("Number is even")
else:
    print("Number is odd")
Number is odd

The above is called an if-else statement. If the condition in the if statement is True, the block of code under the if statement is executed. If the condition is False, the block of code under the else statement is executed. This is also an if-else statement, but with multiple conditions. If the condition in the if statement is True, the block of code under the if statement is executed. If the condition in the elif statement is True, the block of code under the elif statement is executed. If none of the conditions are True, the block of code under the else statement is executed.

Let us look at such an example:

number = 5

if number > 0:
    print("Number is positive")
elif number < 0:
    print("Number is negative")
else:
    print("Number is zero")
Number is positive

Here we check for two conditions, if the number if larger than zero, smaller than zero or neither (the final else statement). The elif statement is short for “else if”, and is used to check multiple conditions. You can have as many elif statements as you want, but only one if and one else statement.

Loops

Loops are used to execute a block of code multiple times. There are two types of loops in Python: for loops and while loops. A for loop is used to iterate over a sequence (like a list, tuple, or string) and execute a block of code for each element in the sequence. A while loop is used to execute a block of code as long as a condition is True.

For loops

In the previous section we looked at complex data types like lists and tuples. Let us use them in a for loop to take a list of numbers, and create a new list with each number squared.

numbers = [1, 2, 3, 4, 5]

squared_numbers = []
for number in numbers:
    squared_numbers.append(number**2)  # ** is the power operator

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

The for loop iterates over the list numbers, and for each number in the list, it appends the square of the number to the list squared_numbers. for loops work equally well with other sequences. Let us look at an example with a dictionary. We will take a dictionary with several people, and will calculate the average age in the group.

persons = {"Alice": 21, "Bob": 27, "Charlie": 37}

sum = 0
for person in persons:
    sum = sum + persons[person]

average_age = sum // len(persons)

print(average_age)
28

The above code iterates through everyone in the persons dictionary, and sums everyone ages. Once the for loop is complete, it then calculates the average age by dividing the sum by the number of people in the list.

About the len Function

The len function takes a sequence (a list, tuple or dictionary) as an argument, and returns the number of elements in the sequence.

for loops with range

The range function is used to generate a sequence of numbers. It takes three arguments: start, stop, and step. The start argument is the first number in the sequence, the stop argument is the number that the sequence stops before, and the step argument is the difference between each number in the sequence.

It is often used in for loops to iterate a certain number of times. Let us look at an example where we construct a long list of numbers based on for and range.

numbers = []
for i in range(1, 20, 1):  # range(start, stop, step)
    numbers.append(i)

print(numbers)
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]

The while loop

Besides the for loop, Python also has a while loop. while is used to execute a block of code as long as a condition is True. It is normally used when you do not know how many times you need to execute a block of code, and you only want to stop when a certain condition is met.

The simplest while loop is one that runs forever. This is done by using the True boolean value as the condition. This is useful when you want to run a program that listens for user input, or a program that runs continuously in the background.

Stopping a Program

To stop a program that runs forever, you can use the Ctrl+C keyboard shortcut. In Jupyter notebooks, you can stop the execution of a cell by clicking the stop button in the toolbar.

while True:
    print("This will run forever")
    break  # This will artificially break out of the loop

while False:
    print("This will never run")
This will run forever

As a more interesting example, let us calculate how many times we would need to fold a piece of paper to reach the moon. The thickness of a piece of paper is 0.1 mm, and the distance to the moon is 384,400 km. We will fold the paper in half each time.

moon_distance = 384000 * 1000 * 1000  # millimeters
paper_thickness = 0.1  # millimeters
folded_thickness = paper_thickness

folds = 0
while folded_thickness < moon_distance:
    folded_thickness *= 2  # This is the same as folded_thickness = folded_thickness * 2
    folds += 1

print(folds)
42

A while loop can also be used in the context of sequences. For example, we can use a while loop to reverse the order of a list of numbers by using the pop method of a list.

About the pop Method

The pop method of a list removes the last element of the list and returns it. If you do not provide an index to the pop method, it will remove the last element of the list.

numbers = [1, 2, 3, 4, 5]
inverse_numbers = []

while numbers:
    inverse_numbers.append(numbers.pop())

print(inverse_numbers)
[5, 4, 3, 2, 1]

break and continue

Sometimes you want to stop a loop before it has finished, or skip the rest of the code in a loop and continue with the next iteration. This is done using the break and continue statements. The break statement is used to exit a loop, and the continue statement is used to skip the rest of the code in a loop and continue with the next iteration.

Let us look at an example of a for loop that iterates over a list of numbers, and stops when it reaches a number that is divisible by 3.

numbers = [10, 17, 21, 31, 56]

for number in numbers:
    if number % 3 == 0:
        print(number)
        break
21

Remember the else in the if-else statement? It can also be used in a loop. The else statement in a loop is executed when the loop has finished iterating over the entire sequence. It is not executed if the loop is exited using a break statement. Let us put that to good use from the previous example.

numbers = [10, 17, 22, 31, 56]

for number in numbers:
    if number % 3 == 0:
        print(number)
        break  # This will break out of the for loop
else:
    print("No number was divisible by 3")
No number was divisible by 3

The continue statement is used to skip the rest of the code in a loop and continue with the next iteration. This is useful when, for example, you want to skip certain elements in a sequence. Let us look at an example where we take a list, and build another list without any numbers which are divisible by 3.

numbers = [10, 17, 21, 31, 56]

without_divisible_by_3 = []
for number in numbers:
    if number % 3 == 0:
        continue
    without_divisible_by_3.append(number)

print(without_divisible_by_3)
[10, 17, 31, 56]

match

The match statement is used to compare a value against a set of patterns, and execute a block of code based on the pattern that matches. It is similar to a series of if-elif-else statements, but is more concise and easier to read. Here is a practical example of a match statement that takes a number, and prints a string based on the number.

number = 1

match number:
    case 0:
        print("Zero")
    case 1:
        print("One")
    case 2:
        print("Two")
    case 3:
        print("Three")
    case _:
        print("Something else")
One

Exercises

  1. Write a program that takes a sequence of numbers, and prints only positive numbers in the sequence.
  2. Write a program which computes the factorial of a number.

Reuse

This work is licensed under CC BY (View License)