Flow controls: Loops · 7 / 26 Theory

Common mistakes with loops

Loops are a classic source of mistakes. Recognising them will save you a lot of time.

1. The unintended infinite loop

If you forget to update the variable in the condition, the while never ends:

i = 1
while i <= 5:
    print(i)
    # i += 1 is missing  → it prints 1 forever

If it happens, interrupt the program (in the console, with Ctrl+C) and check the update.

2. The off-by-one error

for i in range(1, 5):   # only reaches 4
    print(i)

for i in range(1, 6):   # to reach 5 you must write 6
    print(i)

Remember: in range the end is never included. And the first index of a string is 0 and the last one is len(text) - 1.

3. Initializing inside the loop

for i in range(1, 6):
    total = 0        # it is reset on every turn!
    total += i
print(total)         # 5, not 15

The accumulator is initialized before the loop.

4. Product accumulator starting at 0

product = 0
for i in range(1, 6):
    product *= i
print(product)   # 0: you must start at 1

5. Modifying the variable of a for

for i in range(5):
    i = i + 10     # does not change the turns, range goes on
    print(i)       # 10 11 12 13 14

The for variable is reassigned on every turn with the next value of the sequence; it is not a way to control the loop.

6. Indentation

for i in range(3):
    print(i)
print("end")     # outside the loop: shown once

for i in range(3):
    print(i)
    print("end")  # inside: shown three times

7. Comparing numbers with texts in the condition

n = input()
while n != 0:      # always True: "0" is not 0
    n = input()

n = int(input())
while n != 0:      # correct
    n = int(input())

A debugging technique

When a loop does not do what you expect, add a temporary print at the beginning of the block with the key variables. You will see turn by turn which values they hold.

while n > 0:
    print("DEBUG n =", n)
    n = n // 10

Practice with any of the exercises in the lesson; in Digits in a number and Infinite divisions update mistakes are very common.