Loops
The for loop and the range function
The for loop and the range function
A loop lets you repeat an action several times without having to copy the code again. The for loop is used when you know in advance the number of repetitions.
The range function generates a sequence of integers, often used with for:
for i in range(5):
print(i)
This program displays 0, 1, 2, 3, 4: range(5) generates the numbers from 0 to 4 (5 numbers in total, starting from 0 and stopping just before 5). This is a classic trap for beginners: range(5) does not go up to and include 5!
Here is a concrete and useful example: displaying the multiplication table of 7:
for i in range(1, 11):
print("7 x", i, "=", 7 * i)
Here, range(1, 11) generates the numbers from 1 to 10 inclusive. Each time through the loop, the variable i takes a new value (1, then 2, ... up to 10), and the print line is executed with that value.
You can also count down, by adding a third argument to range (the step):
for i in range(10, 0, -1):
print(i)
print("Liftoff!")
This program displays 10, 9, 8... down to 1, then Liftoff!. The -1 tells range to count down instead of counting up.
The for loop is therefore perfectly suited whenever you know in advance how many times an action must be repeated.

