What is a For Loop?
A for loop repeats a block of code for each item in a sequence. It's Python's primary tool for iteration.
for item in sequence:
# code that runs for each item
Looping Over a List
students = ["Chan", "Lee", "Wong", "Cheung"]
for name in students:
print(f"Hello, {name}!")
Looping with range()
range() generates a sequence of numbers:
# 0 to 4 (5 numbers)
for i in range(5):
print(i)
# 1 to 10
for i in range(1, 11):
print(i)
# Even numbers 0 to 10
for i in range(0, 11, 2):
print(i)
# Counting down
for i in range(10, 0, -1):
print(i)
Looping with Index using enumerate()
students = ["Chan", "Lee", "Wong"]
for i, name in enumerate(students):
print(f"{i+1}. {name}")
# Output:
# 1. Chan
# 2. Lee
# 3. Wong
Parallel Iteration with zip()
names = ["Chan", "Lee", "Wong"]
scores = [85, 72, 91]
for name, score in zip(names, scores):
print(f"{name}: {score}")
Looping Over a String
for char in "HKDSE":
print(char)
# Prints H, K, D, S, E on separate lines
Looping Over a Dictionary
grades = {"Chan": "A", "Lee": "B", "Wong": "A"}
# Keys only
for name in grades:
print(name)
# Keys and values
for name, grade in grades.items():
print(f"{name}: {grade}")
Nested Loops
Loops inside loops are essential for 2D data:
# Multiplication table
for i in range(1, 6):
for j in range(1, 6):
print(f"{i*j:3}", end=" ")
print() # new line after each row
# Output:
# 1 2 3 4 5
# 2 4 6 8 10
# 3 6 9 12 15
# 4 8 12 16 20
# 5 10 15 20 25
Accumulator Pattern
The most common use of loops — building up a value:
scores = [85, 72, 91, 68, 79]
# Sum
total = 0
for score in scores:
total += score
print(f"Total: {total}")
# Count passes (>=50)
passes = 0
for score in scores:
if score >= 50:
passes += 1
print(f"Passes: {passes}")
# Find maximum manually
highest = scores[0]
for score in scores:
if score > highest:
highest = score
print(f"Highest: {highest}")
break and continue
# break — exit the loop early
for i in range(10):
if i == 5:
break
print(i) # 0, 1, 2, 3, 4
# continue — skip this iteration
for i in range(10):
if i % 2 == 0:
continue
print(i) # 1, 3, 5, 7, 9
Real HK Example: MTR Fare Calculator
fares = [4.5, 6.5, 8.0, 11.5]
total_spent = 0
for trip_num, fare in enumerate(fares, start=1):
total_spent += fare
print(f"Trip {trip_num}: ${fare}")
print(f"Total: ${total_spent:.2f}")
When to Use For vs While
- Use for when you know how many times to loop (or have a sequence)
- Use while when you loop until a condition changes