Flow controls: Loops · 2 / 26 Theory

The for loop and range

When you know how many times something must be repeated, for is more convenient and safer than while: the control variable is managed for you.

range: a sequence of numbers

for i in range(5):
    print(i)
# 0 1 2 3 4  (one per line)

range(5) produces 0, 1, 2, 3, 4: it starts at 0 and the end is not included.

FormNumbers it producesExample
range(n)from 0 to n-1range(4) → 0, 1, 2, 3
range(a, b)from a to b-1range(2, 6) → 2, 3, 4, 5
range(a, b, step)from a to b-1 jumping steprange(1, 10, 3) → 1, 4, 7
range(a, b, -1)backwardsrange(5, 0, -1) → 5, 4, 3, 2, 1

Examples

# From 1 to 5 (you must write 6 as the end)
for i in range(1, 6):
    print(i)

# Descending odd numbers from 9 to 1
for i in range(9, 0, -2):
    print(i)   # 9 7 5 3 1

# Multiplication table of 7
for i in range(1, 11):
    print(f"7 x {i} = {7 * i}")

Repeating n times

If you do not need the variable, the habit is to call it _:

for _ in range(3):
    print("Hello")

for versus while

  • for: you know how many turns there are (or you go through a sequence).
  • while: the repetition depends on a condition that changes while running.

Practice with Multiplication table and Descending odd numbers.