Courses/Python Mastery/Module 6: Control Flow
Module 6 · Lesson 220 minBeginner

for Loops and range

Lesson goal
Repeat work over sequences without copy-pasting code.

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

code
fruits = ["apple", "banana", "mango"]

for fruit in fruits:
    print(f"I like {fruit}")

Output:

code
I like apple
I like banana
I like mango

Read 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?

code
for i in range(5):
    print("Hello!", i)

Output:

code
Hello! 0
Hello! 1
Hello! 2
Hello! 3
Hello! 4

range(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

code
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:

code
for second in range(10, 0, -1):
    print(second)
print("LIFT OFF! 🚀")

Summing and counting — the accumulator pattern

code
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.2

Start 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

code
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

code
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:

code
1. Aarav
2. Diya
3. Kabir
Aarav: 92
Diya: 95
Kabir: 78

enumerate adds numbers; zip pairs lists together. Both are everywhere in professional code.

Common Errors & Fixes

  • `IndentationError` — the loop body needs indenting under the colon.
  • Loop runs one time too fewrange(5) stops at 4. Use range(1, 6) for 1 through 5.
  • `NameError` using the loop variable after the loop — it exists (holding the last value), but if the list was empty it was never created.
  • Off-by-one chaos — remember: stop is excluded. Write the range, print it, verify.

  • ✅ Checkpoint

  • What does range(3) produce? *(0, 1, 2)*
  • Loop from 10 down to 1? *(for i in range(10, 0, -1))*
  • What's the accumulator pattern? *(Start at 0, += inside the loop, use after)*
  • Loop two lists together? *(zip)*
  • Next: while loops — repeating until something happens, plus break and continue.