Lesson 7
20 min
for, while, range, break and continue to repeat actions.
Definition
A loop is a structure that repeats a block of instructions several times, without having to rewrite it. Each repetition is called an iteration. Python offers two loops:for, which goes through a sequence of values, andwhile, which keeps going as long as a condition remains true.
A loop lets you repeat instructions without rewriting them. Python offers two types of loops:for(when you know how many times to repeat) andwhile(as long as a condition is true).
Imagine you have to display a message 100 times: without a loop, you would need to write 100 identical lines. With a loop, two lines are enough, and if you want to go up to 1000 repetitions, you only change a single number. Loops make code shorter, more readable and easier to modify.
Therange(n)function generates the numbers from 0 to n - 1. Combined withfor, it lets you repeat an action a precise number of times. The variable placed afterfor(herei) takes a new value on each iteration.
for i in range(5):
print(f"Iteration number {i}")
# Displays iterations 0, 1, 2, 3 and 4
range()also accepts a start, an end (excluded) and a step:
for i in range(1, 6): # 1, 2, 3, 4, 5
print(i)
for i in range(0, 20, 5): # 0, 5, 10, 15
print(i)
for i in range(10, 0, -2): # 10, 8, 6, 4, 2 (negative step: counting down)
print(i)forcan go directly through the elements of a sequence, such as the letters of a word or the items of a list (we will cover lists in an upcoming lesson). You then don’t needrange(): the variable receives each element directly.
for letter in "Python":
print(letter)
for fruit in ["apple", "banana", "cherry"]:
print(f"I like {fruit}s")A very common use of loops is to build a result bit by bit. You create a starting variable, called an accumulator, then update it on each iteration.
# Sum of the numbers from 1 to 10
total = 0
for number in range(1, 11):
total += number
print(f"The sum is {total}") # 55
# Count the vowels in a word
word = "programming"
vowels = 0
for letter in word:
if letter in "aeiou":
vowels += 1
print(f"{word} contains {vowels} vowels") # 3whilerepeats a block as long as its condition remains true. You therefore need to make sure that something eventually makes the condition false, otherwise the loop never stops. It’s used when you don’t know in advance how many iterations will be needed, for example to ask for input again until it is valid.
counter = 3
while counter > 0:
print(counter)
counter -= 1
print("Liftoff!")Watch out for infinite loops
If your program runs without stopping, pressCtrl + Cin the terminal to interrupt it. Then check that the variable in your condition is actually modified on each iteration.
range()).# Ask for a password until it is correct
while True:
password = input("Password: ")
if password == "python123":
print("Access granted")
break
print("Incorrect, try again.")
# Display only the odd numbers
for i in range(1, 10):
if i % 2 == 0:
continue
print(i)
A loop can contain another one. On each iteration of the outer loop, the inner loop is replayed in full. This is the technique used to display tables or grids.
for row in range(1, 4):
for column in range(1, 4):
print(f"{row} x {column} = {row * column}")
print("---")fororwhileline.range(1, 5)stops at 4. To go up to 5, you need to writerange(1, 6).counter -= 1in the previous example, the loop would be infinite.Exercise
Going further
while, indicating “too high” or “too low”, until the user finds it. Count the number of attempts and display it at the end.