The for Loop and range()
Python's for is not a counted loop. It is a for-each: it walks
through the items of a sequence.
for name in ["Anjali", "Rahul", "Meera"]:
print(name)
There is no counter, no condition, no increment. To count, you iterate
over a sequence of numbers — and range() produces one.
range()
| Form | Produces |
|---|---|
range(5) | 0, 1, 2, 3, 4 |
range(1, 6) | 1, 2, 3, 4, 5 |
range(1, 10, 2) | 1, 3, 5, 7, 9 |
range(10, 0, -1) | 10, 9, 8, … 1 |
range(5, 1) | nothing — empty |
Two rules that account for most mistakes:
1. The start is included, the stop is excluded. range(1, 6) gives
1 to 5. To count 1 to n you write range(1, n + 1).
2. Counting down needs a negative step. range(10, 0, -1) stops at 1,
not 0, because the stop is still excluded.
How many iterations?
For range(a, b) the count is — no +1, unlike the pseudocode
FOR i ← a TO b in Module 2, which included both ends. Mixing the two
conventions is the single commonest off-by-one in this course.
Pseudocode: FOR i ← 1 TO 5 runs 5 times (1,2,3,4,5)
Python: range(1, 5) runs 4 times (1,2,3,4)
range(1, 6) runs 5 times (1,2,3,4,5)
Iterating a sequence directly
If you don't need the index, don't create one:
total = 0
for mark in marks: # preferred
total += mark
for i in range(len(marks)): # avoid when i is unused
total += marks[i]
When you need both index and value, enumerate gives you both:
for i, mark in enumerate(marks):
print(f"Student {i + 1}: {mark}")
Accumulator pattern
Same as Module 2 — initialise before the loop, update inside:
total = 0 # 0 for sums
for x in numbers:
total += x
product = 1 # 1 for products
for x in numbers:
product *= x
Loop variable after the loop
The loop variable survives, holding the last value used:
for i in range(3):
pass
print(i) # 2
If the range was empty the variable never existed, and referring to it
raises NameError. Don't rely on it.
break, continue, else
for x in numbers:
if x < 0:
print("Found a negative")
break # leave the loop entirely
if x == 0:
continue # skip to the next item
print(x)
else:
print("No negative found")
The for … else is unusual: the else runs only if the loop finished
without break. It is genuinely useful for searches, and it is
examinable because it surprises people.