for Loops and range
Copy-pasting the same line five times is a smell. The for loop says *"do this for every item"* — and it's the workhorse behind every leaderboard, dashboard, and data processor in this course.
Looping over a list
fruits = ["apple", "banana", "mango"]
for fruit in fruits:
print(f"I like {fruit}")Output:
I like apple
I like banana
I like mangoRead it as: *"for each fruit in fruits, do the indented block."* Each pass, fruit holds the next item — apple first, then banana, then mango. The variable name is yours; for fruit in fruits: is the idiomatic shape.
range() — looping a number of times
What if there's no list — you just want something done 5 times?
for i in range(5):
print("Hello!", i)Output:
Hello! 0
Hello! 1
Hello! 2
Hello! 3
Hello! 4range(5) produces the numbers 0, 1, 2, 3, 4 — five numbers, starting at 0, top excluded. The same "stop excluded" rule as slicing.
range's three faces
range(5) # 0 1 2 3 4 — stop only
range(2, 6) # 2 3 4 5 — start, stop
range(0, 10, 2) # 0 2 4 6 8 — start, stop, STEP
range(10, 0, -1) # 10 9 8 ... 1 — negative step counts down!Countdowns, every-3rd-item, descending lists — the third parameter does it all:
for second in range(10, 0, -1):
print(second)
print("LIFT OFF! 🚀")Summing and counting — the accumulator pattern
marks = [85, 92, 78, 90]
total = 0
for mark in marks:
total += mark # the += accumulator!
print(f"Total: {total}")
print(f"Average: {total / len(marks):.1f}") # 86.2Start a variable at 0, grow it inside the loop, use it after. This pattern — accumulator — powers every total, count, and maximum you'll ever compute. (You saw it in the expense tracker and quiz app already.)
Building lists with loops
squares = []
for n in range(1, 6):
squares.append(n ** 2)
print(squares) # [1, 4, 9, 16, 25]Start empty, append inside the loop. (Module 10's comprehensions will compress this to one line — earn it first.)
Looping two things at once: enumerate and zip
names = ["Aarav", "Diya", "Kabir"]
scores = [92, 95, 78]
# Need the position too? enumerate:
for i, name in enumerate(names, start=1):
print(f"{i}. {name}")
# Two parallel lists? zip:
for name, score in zip(names, scores):
print(f"{name}: {score}")Output:
1. Aarav
2. Diya
3. Kabir
Aarav: 92
Diya: 95
Kabir: 78enumerate adds numbers; zip pairs lists together. Both are everywhere in professional code.
Common Errors & Fixes
range(5) stops at 4. Use range(1, 6) for 1 through 5.✅ Checkpoint
range(3) produce? *(0, 1, 2)*Next: while loops — repeating until something happens, plus break and continue.