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
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.
iis the loop counter; here we do not use its value, we just want five repeats.
Using the counter
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.itakes 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
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
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 early
range 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 atstartand stops beforestop.range(start, stop, step)counts in steps.- The loop counter
iis available inside the loop.