Skip to content

Loops

Loops are a way of executing operations several times. Two types of loops are often used, which are identical in terms of content but focus on different aspects: for and while.

The rule of thumb is: If the number of loop passes is known, the for loop is used. If the number of loop passes is unknown, the while loop is used. Although Python allows both, the code is much easier to read with this rule.

In a for loop, a sequence of elements is run through, i.e. any iterable. This is a list, for example. In each loop pass, the next element of the sequence is written to a variable. The loop ends when the sequence is complete.

for i in [1, 2, 3]:
    print (i)

A condition is checked in a while loop. As long as this is true, the loop block is executed over and over again. The loop only ends as soon as the condition is no longer true at the next completion of the block. However, the last loop block is always executed at the end:

i = 1
while i <= 3:
    print (i)
    i += 1
    print ("Done")

Here, the numbers 1-3 and "Done" are output alternately. The last "Done" is also output, although at this point i is already 4 and therefore the condition in the loop header is no longer fulfilled.

Skip individual elements

If you want to skip parts of the list, you can use the keyword continue:

for i in [1, 2, 3, 4, 5, 6]:
    if i % 2 == 0:
        continue
    print (i)

Only the odd numbers are output here: each loop block is skipped as soon as the keyword continue is reached, which is not permitted outside of loops.

Cancel early

Similar to continue, which ends the current loop run prematurely, the entire loop can be cancelled even though not all elements have been run through or the cancellation condition has been fulfilled. The keyword break is used for this purpose:

for i in [1, 2, 3, 4, 5, 6]:
    if i == 4:
        break
    print (i)

The numbers 1-3 are output here, then the loop and the current loop pass are cancelled. This is useful, for example, if you want to find a single element in a list.

At first glance, it is confusing that else can be combined with loops (both for and while). The else is then executed if the loop has not been cancelled by a break. This is useful, for example, if you want to cover a standard case:

values = [1, 2, 3, 4, 5, 6]

# find and print a number > 10
for value in values:
    if value > 10:
        print (value)
        break
else:
    print ("This does not contain a number greater than 10.")

This saves the otherwise necessary auxiliary variable that checks whether an element has been found:

values = [1, 2, 3, 4, 5, 6]
found = False
for value in values:
    if value > 10:
        print (value)
        found = True
        break
if not found:
    print ("This does not contain a number greater than 10.")

Indexing

If you want to know how many elements of a list you have in front of you, you can use enumerate:

for i, value in enumerate([1, 2, 3, 4, 5, 6]):
    print (i, value)

Here i always contains the index of the element (as always starting at 0), value the value of the element.

Character strings

Strings are also iterable, whereby they are regarded as a list of characters:

for char in "Hello":
    print (char)

Outputs the characters "H", "e", "l", "l", "o".

Dictionaries

You can iterate over all elements of a dictionary. The key-value pair is always returned:

elements = {"H": "Hydrogen", "He": "Helium", "Li": "Lithium"}
for element, name in elements.items():
    print (element, name)

Displays the elements and their names.