Lesson 8 — Repetition

Loops

Python's for loop iterates over any iterable — strings, lists, ranges, files, generators. The while loop handles condition-based repetition. Both have an else clause unique to Python.

PYTHON — for loops
# for with range() — most common form:
for i in range(1, 6):
    print(f"Iteration {i}")

# range(start, stop, step) — stop is exclusive:
for i in range(0, 10, 2):
    print(i, end=" ")  # 0 2 4 6 8
print()

# Iterating any sequence:
names = ["Thandi", "Sipho", "Lerato", "Bongani"]
for name in names:
    print(f"Hello, {name}!")

# enumerate() — gives index and value:
for i, name in enumerate(names, start=1):
    print(f"{i}. {name}")

while Loop

PYTHON — while loop
balance = 1000
withdrawal = 250

while balance > 0:
    print(f"Balance: R{balance}")
    balance -= withdrawal

print("Account empty.")

# Input validation with while:
mark = -1
while not (0 <= mark <= 100):
    try:
        mark = float(input("Enter mark (0-100): "))
    except ValueError:
        print("Please enter a number.")

Loop else

Python's else clause on a loop runs only when the loop completes without a break — useful for search patterns.

PYTHON — Loop else and flow control
names = ["Thandi", "Sipho", "Lerato"]

for name in names:
    if name == "Sipho":
        print(f"Found {name}!")
        break
else:
    print("Name not found in list.")  # runs only if no break occurred

# break and continue:
for i in range(1, 11):
    if i % 2 == 0:
        continue  # skip even numbers
    if i > 7:
        break     # stop at 7
    print(i, end=" ")  # 1 3 5 7

Comprehension Preview

Python loops are often replaced with comprehensions for conciseness — covered fully in the Lists lesson.

PYTHON — Comprehension preview
# Traditional loop:
squares = []
for i in range(1, 6):
    squares.append(i ** 2)

# List comprehension — same result, one line:
squares = [i ** 2 for i in range(1, 6)]
print(squares)  # [1, 4, 9, 16, 25]

Practice Task

Your Turn

Write three programs: (1) Fibonacci sequence — print first 20 numbers using a while loop. (2) Prime sieve — use nested for loops with break and loop else to find all primes up to 50. (3) Multiplication table — use nested for loops and f-strings to print a well-aligned 10×10 table.

Common Mistakes

  • range(10) produces 0–9, not 1–10. Use range(1, 11) for 1–10.
  • Forgetting the colon after for/while.
  • Modifying a list while iterating it — iterate over a copy: for item in list(my_list):.
  • Infinite while — always verify the condition eventually becomes False.

Professional Tip

Python's for loop doesn't give you an index by default, but enumerate() adds one cleanly. Avoid the Java pattern of for i in range(len(list)) when you just need values — use for item in list.

Mini Quiz

What does range(2, 10, 3) produce?