Skip to content

Loops

Loops

Loops are generally used to repeat sections of code instead of spelling them out again. In Python, two types of loop are distinguished: the while- and the for-loop. The repetitions within a loop are called iterations.

Loops inside loops

There are cases where loops have to be placed inside other loops. This is called nesting or nested loops. In such cases, these loops get distinguished by talking about inner and outer loops.

In the following example, the for-loop is nested inside the while-loop.

while not food_is_spicy:
    for spice in [salt, pepper, chilli]:
        throw_in_pot(spice)
    food_is_spicy = taste_food()
Here, the for-loop would be considered the inner loop, which gets executed completely for each iteration of the outer while-loop. Nesting loops tends to increase the complexity of a program considerably, making it harder to read, understand and maintain. To counteract this, a common strategy is to extract the inner loops into their own functions so they can be handled separately.

while-Loops

As long as a condition is fulfilled, repeat a section of code.

Use Case

Looping over code when it is not initially clear, how many iterations will be required or when a condition will change.

Request the user to input the word “exit”. Repeat the request until the correct input is made.

user_input = None

while not user_input == "exit":
    user_input = input("Please type the word \"exit\": ")

Note that the variable user_input needs to exist before the loop, so it can be compared in the beginning of the loop.

for-Loops

Go over each element of a given collection of data.

Use Case

Looping over code where the amount of iterations is predictable.

Data sources for the loop

Anything that is iterable can serve as a data souce in for-loops. This can be (amongst others) Lists, Sets, Tuples, Dictionaries, Ranges, or Strings.

Example 1

Using a for-loop to print all numbers in a fixed list and their square.

for number in [2, 3, 5, 7, 11, 13]:
    print(number, number ** 2)

The break Keyword

This keyword will abort the execution of the loop it is in. The code will resume after the loop as usual. In the case of nested loops, only the loop that the keyword is in will be affected.

The following loop will print a shopping list and stop as soon as the word "end" is reached.

shopping_list = ["potato", "apple", "end", "banana"]

for item in shopping_list:
    if item == "end":
        break
    print(item)

The continue Keyword

This keyword is used inside a loop body. It will trigger the loop to skip the rest of the current iteration and start the next one right away. Note that the keyword only affects the loop it is directly in, not any outer loops.

Example 1

In the following loop, we sum all values from 0 to 99, but skip each number ending with 3.

total = 0

for number in range(100):
    if number % 10 == 3:
        print("Skipping number", number)
        continue
    total = total + number

print("Sum from 0 … 99 (without numbers ending on 3):", total)

Example 2

List all files in a folder. The continue here is used to skip everything that is not a file (like sub-folders).

from pathlib import Path

folder = Path("/path/to/the/folder")

for entry in folder:
    if not entry.is_file():
        continue
    file_name = entry.name
    file_size = entry.stat().st_size
    print(f"{file_name}: {file_size} Bytes")