24 min read
for Loops and range()
Repeat code a set number of times with for and range(start, stop, step) — odd numbers, multiples of 5 and a times table.
The for Loop
Repeat 5 timesPython
for count in range(5): print("Label printed", count)Expected output
Label printed 0 Label printed 1 Label printed 2 Label printed 3 Label printed 4
for repeats the indented block once for each value. range(5) gives the numbers 0, 1, 2, 3, 4 — five numbers, starting at 0 and stopping before 5. The loop variable (count) takes each value in turn.
range(start, stop, step)
| The three forms of range() | |
|---|---|
Odd Numbers from 1 to 9
The loop as a flowchart
Read this flowchart as text
- Terminator: Start (then → number = 1)
- Process: number = 1 (then → number <= 9?)
- Decision: number <= 9? (Yes → OUTPUT number; No → Stop)
- Input/output: OUTPUT number (then → number = number + 2)
- Terminator: Stop
- Process: number = number + 2 (then → number <= 9?)
odd.pyPython
for number in range(1, 10, 2): print(number)Expected output
1 3 5 7 9
The flowchart's three loop parts — start value (1), condition (≤ 9) and change (+ 2) — are all packed into range(1, 10, 2).
Multiples of 5 on One Line
multiples.pyPython
for n in range(5, 51, 5): print(n, end=" ")print()Expected output
5 10 15 20 25 30 35 40 45 50
end=" " prints a space instead of a new line, so the numbers stay on one line. The final print() moves to a new line at the end.
A Times Table
Times table flowchart
Read this flowchart as text
- Terminator: Start (then → INPUT n)
- Input/output: INPUT n (then → i = 1)
- Process: i = 1 (then → i <= 10?)
- Decision: i <= 10? (Yes → OUTPUT n, "x", i, "=", n × i; No → Stop)
- Input/output: OUTPUT n, "x", i, "=", n × i (then → i = i + 1)
- Terminator: Stop
- Process: i = i + 1 (then → i <= 10?)
times_table.pyPython
n = int(input("Which times table? ")) for i in range(1, 11): print(f"{n} x {i} = {n * i}")Expected output
Which times table? 7 7 x 1 = 7 7 x 2 = 14 7 x 3 = 21 7 x 4 = 28 7 x 5 = 35 7 x 6 = 42 7 x 7 = 49 7 x 8 = 56 7 x 9 = 63 7 x 10 = 70
Adding Up in a Loop
weekly_sales.pyPython
total = 0for day in range(1, 8): sales = float(input(f"Sales on day {day}: ")) total += salesprint(f"Weekly sales: LKR {total:,.2f}")Expected output
Sales on day 1: 12500 Sales on day 2: 9800 Sales on day 3: 11200 Sales on day 4: 10400 Sales on day 5: 15300 Sales on day 6: 18750 Sales on day 7: 16900 Weekly sales: LKR 94,850.00
Practice
More lessons in Python Programming · Next: while Loops · Previous: elif and Nested if
