Lesson 7 / 1164%

Lesson 7

Loops

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.

Why loops?

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.

The for loop and range()

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_range.py
for i in range(5):
    print(f"Iteration number {i}")

# Displays iterations 0, 1, 2, 3 and 4
Screenshot: a terminal showing the result of running the for_range.py script, with the five messages displayed one below the other.

range()also accepts a start, an end (excluded) and a step:

range_options.py
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)

Going through a string or a list

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.

traversal.py
for letter in "Python":
    print(letter)

for fruit in ["apple", "banana", "cherry"]:
    print(f"I like {fruit}s")

Calculating with a loop

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.

accumulator.py
# 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")   # 3

The while loop

whilerepeats 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.

while.py
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.

Choosing between for and while

  • Use for when you know the number of repetitions or when you’re going through a sequence (letters, list items, numbers from arange()).
  • Use while when the repetition depends on a condition that can change at any time (input to validate, a game to continue, a value to reach).

break and continue

  • break: exits the loop immediately.
  • continue: skips the rest of the current iteration and moves on to the next one.
break_continue.py
# 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)
Screenshot: a terminal showing the result of running the break_continue.py script, with the messages displayed one below the other.

Nested loops

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.

nested.py
for row in range(1, 4):
    for column in range(1, 4):
        print(f"{row} x {column} = {row * column}")
    print("---")

Common errors

  • Forgetting the colon at the end of thefororwhileline.
  • Forgetting that range() excludes the end:range(1, 5)stops at 4. To go up to 5, you need to writerange(1, 6).
  • Not modifying the while condition: withoutcounter -= 1in the previous example, the loop would be infinite.
  • Bad indentation of the loop body: only the lines shifted by 4 spaces are repeated.

Exercise

Display the multiplication table of a number entered by the user (from 1 to 10), in the form “7 x 3 = 21”. Then calculate the sum of all the results with an accumulator.

Going further

Write a “guess the number” game: the program picks a fixed number between 1 and 20, and asks for a guess again withwhile, indicating “too high” or “too low”, until the user finds it. Count the number of attempts and display it at the end.