🌱
Basic
for · while · range · break · continue · else
Week 5 — Loops
Automate repetitive tasks with for and while loops. Master range(), break, continue, and the rarely-known loop else clause.
forwhilerangebreakcontinueloops
Duration
⏱ 2.5 hours
Level
📊 Beginner
Prerequisite
🎯 Week 4
OUTCOME
Build a multiplication table generator and a number guessing game
What you'll learn
- 1Iterate over a range with for/range()
- 2Use while for condition-driven loops
- 3Control loop flow with break and continue
- 4Explain the loop else clause
- 5Nest loops to produce 2D output
1. for Loop & range()
python
for i in range(5): # 0 1 2 3 4
print(i, end=' ')
for i in range(1, 6): # 1 2 3 4 5
print(i, end=' ')
for i in range(0, 10, 2): # 0 2 4 6 8
print(i, end=' ')ℹ️
range(stop), range(start, stop), range(start, stop, step). The stop value is exclusive.
2. while Loop
python
n = 1
while n <= 5:
print(n)
n += 1
# Infinite loop with break
while True:
cmd = input("Command (quit to exit): ")
if cmd == "quit":
break
print(f"You entered: {cmd}")3. break, continue, else
python
for i in range(1, 11):
if i == 5:
continue # skip 5
if i == 8:
break # stop at 8
print(i, end=' ') # 1 2 3 4 6 7
for i in range(2, 10):
for j in range(2, i):
if i % j == 0:
break
else: # only runs if no break
print(f"{i} is prime")4. Nested Loops
python
for row in range(1, 4):
for col in range(1, 4):
print(f"{row}×{col}={row*col}", end=' ')
print()Output: 1×1=1 1×2=2 1×3=3 / 2×1=2 2×2=4 2×3=6 / 3×1=3 3×2=6 3×3=9
5. Common Mistakes
- Forgetting to increment the counter in a while loop → infinite loop. Always update the condition variable.
- range(1, 10) ends at 9, not 10. Off-by-one errors are very common.
- Modifying a list while iterating over it — iterate over a copy instead: for x in lst[:].
💻 Examples
Run these examples and check the output yourself.
01_times_table.py— Multiplication table 1–9
CODE
for i in range(1, 10):
for j in range(1, 10):
print(f"{i*j:3d}", end='')
print()
02_sum_1_to_n.py— Sum 1 to N using for and while
CODE
n = int(input("N: "))
# for version
total = sum(range(1, n+1))
print(f"for: {total}")
# while version
total, i = 0, 1
while i <= n:
total += i
i += 1
print(f"while: {total}")
▶ Output
N: 100
for: 5050
while: 505003_guess_number.py— Number guessing game with limited attempts
CODE
import random
secret = random.randint(1, 100)
attempts = 0
while True:
guess = int(input("Guess (1-100): "))
attempts += 1
if guess < secret:
print("Too low!")
elif guess > secret:
print("Too high!")
else:
print(f"Correct! It took {attempts} attempts.")
break
📝 Exercises
Try them yourself first, then open the solution to compare.
Exercise 1
FizzBuzz
Goal: Print 1 to 100, replacing multiples of 3 with Fizz, 5 with Buzz, 15 with FizzBuzz.
Requirements
- Use a for loop with range(1, 101)
- Check divisibility with %
- Print FizzBuzz for multiples of 15 first
▶Toggle solution
SOLUTION
for i in range(1, 101):
if i % 15 == 0:
print('FizzBuzz')
elif i % 3 == 0:
print('Fizz')
elif i % 5 == 0:
print('Buzz')
else:
print(i)
Exercise 2
Star Pyramid
Goal: Print a right-aligned pyramid of stars.
Requirements
- Read height N from input
- Row k prints (N-k) spaces then k stars
- Use nested loops
Sample I/O
N: 5
*
**
***
****
*****▶Toggle solution
SOLUTION
n = int(input('N: '))
for i in range(1, n+1):
print(' ' * (n-i) + '*' * i)
Example code / lecture materials
All lecture materials and example code are openly available on GitHub.
View on GitHub ↗