For-loops

In a computer program you often encounter a (small) set of instructions that you want to execute multiple times. The way to do and steer that is by using loops. On this page we discuss the format and features of for-loops.

Loops to repeat instructions

A for-loop is used when you want to repeat a set of instructions. For example, if you want to print the numbers from 1 to 10 on the screen, you could do that with ten separate print-statements, but you could also use the following construction:

for x in range(1, 11):
    print(f"x now has the value {x}")

This program has as output:

x now has the value 1
x now has the value 2
x now has the value 3
...
x now has the value 10

The loop starts by setting the value of x to 1 and then executing all instructions in the loop one by one. This is called an iteration. After that, x is assigned the value 2 and again all instructions are executed. In this simple program there is only a single instruction: print the value of x, but we can of course expand the number of instructions. The most important notion is that the program changes the variable x _after_ each cycle.

There are a few important things to note: