For Loop & Range
The for loop iterates over a sequence a definite number of times.
Combined with the range() function, it gives you precise control over start, stop, and
step values — making it perfect for counting, iterating over sequences, and generating number
patterns.
Learning Objectives
- 11.1.2.4 Write program code using a For loop
- 11.1.2.5 Define a range of values for a loop
Conceptual Anchor
The Measuring Tape Analogy
A for loop with range() is like walking along a measuring tape.
range(start, stop, step) tells you: where to start, where to
stop
(but not including this mark), and how big each step is. Once you reach or pass
the stop mark,
you're done — you know exactly how many steps you'll take before you begin.
Rules & Theory
range() Function
| Form | Meaning | Example | Values Generated |
|---|---|---|---|
range(stop) |
0 to stop-1, step 1 | range(5) |
0, 1, 2, 3, 4 |
range(start, stop) |
start to stop-1, step 1 | range(2, 6) |
2, 3, 4, 5 |
range(start, stop, step) |
start to stop-1, step N | range(0, 10, 2) |
0, 2, 4, 6, 8 |
range(start, stop, -step) |
Counting down | range(5, 0, -1) |
5, 4, 3, 2, 1 |
Critical: Stop value is EXCLUDED
range(1, 5) generates 1, 2, 3, 4 — NOT including 5. This is the
most common source of off-by-one errors. To include 5, use range(1, 6).
For Loop Patterns
# Pattern 1: Simple counting
for i in range(5): # i = 0, 1, 2, 3, 4
print(i)
# Pattern 2: Custom range
for i in range(1, 11): # i = 1, 2, ..., 10
print(i)
# Pattern 3: Step
for i in range(0, 21, 5): # i = 0, 5, 10, 15, 20
print(i)
# Pattern 4: Countdown
for i in range(10, 0, -1): # i = 10, 9, ..., 1
print(i)
print("Go!")
# Pattern 5: Iterating over a string
for char in "Python":
print(char) # P y t h o n (each on new line)
# Pattern 6: Accumulator with for
total = 0
for i in range(1, 101):
total += i
print("Sum 1-100:", total) # 5050For vs While
| Aspect | for loop | while loop |
|---|---|---|
| Use when | Number of iterations is known | Number of iterations is unknown |
| Counter | Managed automatically by range() | You must manage manually |
| Infinite loop risk | Very low | High if condition not updated |
| Example | Process exactly 10 items | Read until user types "quit" |
Worked Examples
1 Multiplication Table
num = int(input("Enter a number: ")) # e.g., 7
for i in range(1, 11):
result = num * i
print(f"{num} x {i} = {result}")
# Output for 7:
# 7 x 1 = 7
# 7 x 2 = 14
# ...
# 7 x 10 = 702 Even Numbers in a Range
start = int(input("Start: ")) # e.g., 1
end = int(input("End: ")) # e.g., 20
print("Even numbers:")
for i in range(start, end + 1):
if i % 2 == 0:
print(i, end=" ")
print()
# Alternative using step:
for i in range(2, end + 1, 2):
print(i, end=" ")3 Power Table with Trace
# Print powers of 2 from 2^0 to 2^8
print("n\t2^n")
print("-" * 16)
for n in range(9):
print(f"{n}\t{2**n}")
# Trace table:
# n | 2**n | Output
# 0 | 1 | 0 1
# 1 | 2 | 1 2
# 2 | 4 | 2 4
# 3 | 8 | 3 8
# ...
# 8 | 256 | 8 2564 break and continue
# break — exit the loop immediately
for i in range(1, 100):
if i * i > 50:
print(f"First square > 50: {i}^2 = {i*i}")
break
# continue — skip to the next iteration
for i in range(1, 11):
if i % 3 == 0:
continue # Skip multiples of 3
print(i, end=" ")
# Output: 1 2 4 5 7 8 10Pitfalls & Common Errors
Modifying the Loop Variable
Changing i inside a for loop has no effect — it resets at the start of each
iteration. Unlike while, the for loop controls i automatically.
Empty Range
range(5, 2) produces no values (start > stop with positive step). For counting down,
use a negative step: range(5, 2, -1).
range() with Float
range(0.0, 1.0, 0.1) causes a TypeError. range() only
works with integers.
Pro-Tips for Exams
Range Counting Formula
range(a, b)producesb - avaluesrange(a, b, s)producesceil((b - a) / s)values- If the question says "from 1 to N including N", use
range(1, N + 1) - When tracing, write out the sequence generated by range() first, then iterate
Graded Tasks
Write the values generated by: range(3, 15, 3) and
range(10, 0, -2).
Explain why range(1, 10) does not include 10. How would you include it?
Write a program that calculates the factorial of N (N!) using a for loop.
Write a program to print all odd numbers between 1 and 50 using range() with a
step.
How many times does for i in range(2, 100, 7) execute? List the first 5 and last
2 values of i.
Create a program that prints an alphabet pattern: Line 1: A, Line 2: AB, Line 3: ABC, ...,
Line 26: ABC...XYZ. Use chr() and ord().
Self-Check Quiz
range(5) generate?range(2, 8, 2) produce?range() with floats?break do inside a for loop?