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.
| Form | Numbers it produces | Example |
|---|---|---|
range(n) | from 0 to n-1 | range(4) → 0, 1, 2, 3 |
range(a, b) | from a to b-1 | range(2, 6) → 2, 3, 4, 5 |
range(a, b, step) | from a to b-1 jumping step | range(1, 10, 3) → 1, 4, 7 |
range(a, b, -1) | backwards | range(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.