Loops: for & while
Repeat actions easily — Python’s loops are wonderfully simple.
What you will learn
- Loop with for and range()
- Loop with while
- Loop over a list
for loops
A loop lets you repeat the same work without copying lines. for repeats once for each item in a sequence. range(n) is a handy helper that produces the numbers 0 up to (but not including) n.
for i in range(5):
print("Number", i)Read this as “for each number in the range 0 to 4, do the indented line.” The variable i holds the current number on each pass: first 0, then 1, 2, 3, 4 — five times in total. The indented print runs once per pass, so you get five lines. range(5) starts at 0 and stops before 5, which is why the last number is 4, not 5.
Note: Output: Number 0 Number 1 Number 2 Number 3 Number 4
Loop a list directly
You do not need range to loop a list — for can walk through the items themselves, which is cleaner and reads like English.
fruits = ["apple", "mango", "banana"]
for fruit in fruits:
print(fruit)The first line makes a list of three fruits. The loop then says “for each fruit in fruits…” — on each pass the variable fruit becomes the next item ("apple", then "mango", then "banana") and the indented line prints it. The loop ends automatically when the list runs out.
Note: Output: apple mango banana
while loops
A while loop repeats as long as a condition stays true — use it when you do not know in advance how many times to loop. You must change something inside the loop so the condition eventually becomes false, or it will run forever.
count = 1
while count <= 3:
print("Count", count)
count = count + 1Step by step: count starts at 1. Python checks the condition is count ≤ 3? — true, so it prints Count 1 and then the last line bumps count up to 2. It checks again (still ≤ 3), prints Count 2, raises count to 3, checks again, prints Count 3, raises count to 4. Now 4 ≤ 3 is false, so the loop stops. That last count = count + 1 line is what stops it from looping forever.
Note: Output: Count 1 Count 2 Count 3
Q. What numbers does range(3) produce?
✍️ Practice
- Print numbers 1 to 10 with a for loop.
- Loop a list of your favourite foods and print each.
🏠 Homework
- Print a multiplication table for a number using a loop.