08-count-controlled-for.py
python-for-j277 / control-flow  ·  Lesson 08
Lesson 08 — Control flow

Iteration: Count-controlled For Loops

Repeat a set number of times with range().

When you know exactly how many times to repeat, use a count-controlled loop with range(). It counts for you.

Repeating a fixed number of times

repeat.py
for i in range(5):
    print("Hello")
Output
Hello
Hello
Hello
Hello
Hello
How it works
  • range(5) produces the numbers 0, 1, 2, 3, 4 — five numbers in total.
  • The loop runs once for each number, so 'Hello' prints five times.
  • i is the loop counter; here we do not use its value, we just want five repeats.

Using the counter

counter.py
for i in range(5):
    print("Number", i)
Output
Number 0
Number 1
Number 2
Number 3
Number 4
How it works
  • range(5) counts from 0 up to (but not including) 5.
  • i takes each value in turn, so it prints 0 to 4.
  • Counting from 0 is normal in programming — get used to it now, it matters for arrays.

Choosing where to start and stop

startstop.py
for i in range(1, 6):
    print(i)
Output
1
2
3
4
5
How it works
  • range(1, 6) starts at 1 and stops before 6, giving 1 to 5.
  • The first number is the start (included); the second is the stop (not included).

Counting in steps

step.py
for i in range(0, 11, 2):
    print(i)
Output
0
2
4
6
8
10
How it works
  • A third number is the step — how much to add each time.
  • range(0, 11, 2) goes up in twos: 0, 2, 4... stopping before 11.
Stops one earlyrange always stops before the second number. range(1, 6) gives 1 to 5, not 1 to 6.
When to use itUse a count-controlled loop when you know the exact number of repeats.

What you have learned

  • range(n) gives 0 up to n − 1.
  • range(start, stop) starts at start and stops before stop.
  • range(start, stop, step) counts in steps.
  • The loop counter i is available inside the loop.