Loops: for & while
1 min read3 lessons in topic
Learning objective
By the end of this lesson you will be able to repeat actions with for and while loops.
Loops repeat a block of code. Use for when you know how many times to repeat; use while when you repeat until a condition changes.
for loops with range
for i in range(5):
print("Iteration", i)range(5) produces 0, 1, 2, 3, 4. range(1, 6) produces 1 to 5.
Looping over a list
courses = ["Python", "Databases", "Networks"]
for course in courses:
print("Studying", course)while loops
count = 0
while count < 3:
print("Count:", count)
count += 1break and continue
for n in range(10):
if n == 3:
continue # skip 3
if n == 6:
break # stop at 6
print(n)- for — iterate over a fixed sequence
- while — repeat while a condition is true
- break — exit the loop early
- continue — skip to the next iteration
Code playground
Run and edit the starter code — experiment freely.
python · runnable
Output appears here when you press Run.
Practice exercise
Print the multiplication table for 7 (7 × 1 to 7 × 12) using a loop.
Check your understanding
1. What does range(3) produce?
2. Which statement ends a loop immediately?
Self-graded — answer then check below.