Python Loops: for & while
A loop repeats a block of code. Use a for loop to go through every item in a collection, and a while loop to repeat until a condition changes. Loops are behind almost every practice program on this site.
- Loop over lists, strings and dicts with for
- Count with range()
- Repeat until a condition with while
- Control loops with break, continue and else
The for loop
A for loop takes each item from a collection in turn and runs the block once per item.
browsers = ["chromium", "firefox", "webkit"] for browser in browsers: print("Testing on", browser)print("All browsers done")Testing on chromium Testing on firefox Testing on webkit All browsers done
It works with anything you can iterate over, including strings, tuples, sets, dicts and files:
for ch in "SQA": print(ch)S Q A
Count with range()
range() produces a sequence of numbers on demand. It stops before the end value.
| Call | Numbers |
|---|---|
range(5) | 0, 1, 2, 3, 4 |
range(2, 6) | 2, 3, 4, 5 |
range(0, 10, 3) | 0, 3, 6, 9 |
range(5, 0, -1) | 5, 4, 3, 2, 1 |
for i in range(1, 6): print(i, "squared is", i * i) print(list(range(10, 0, -2)))1 squared is 1 2 squared is 4 3 squared is 9 4 squared is 16 5 squared is 25 [10, 8, 6, 4, 2]
Index and value: enumerate()
steps = ["open page", "log in", "add to cart"] for number, step in enumerate(steps, start=1): print(f"Step {number}: {step}")Step 1: open page Step 2: log in Step 3: add to cart
Two lists side by side: zip()
names = ["Asha", "Ravi", "Meena"]scores = [91, 78, 85] for name, score in zip(names, scores): print(f"{name:6} {score}")Asha 91 Ravi 78 Meena 85
Loop over a dictionary
stock = {"pen": 40, "notebook": 0, "bag": 7} for item, qty in stock.items(): status = "out of stock" if qty == 0 else f"{qty} left" print(item, "-", status)pen - 40 left notebook - out of stock bag - 7 left
The while loop
while repeats as long as its condition is true. Make sure something in the loop changes the condition, or it never stops.
balance = 1000year = 0 while balance < 2000: balance *= 1.08 # 8% growth per year year += 1 print(f"Doubled after {year} years: {balance:.2f}")Doubled after 10 years: 2158.92
while True: loops forever unless a break stops it. If a program seems stuck, press Ctrl+C in the terminal to stop it.
break and continue
breakleaves the loop immediately.continueskips the rest of this pass and goes to the next item.
numbers = [4, 7, -1, 12, 0, 9] for n in numbers: if n < 0: print("skip negative", n) continue if n == 0: print("zero found, stopping") break print("processing", n)processing 4 processing 7 skip negative -1 processing 12 zero found, stopping
else on a loop
A loop’s else block runs only if the loop finished without break. It is perfect for “search, and report if not found”:
users = ["asha", "ravi", "meena"]wanted = "john" for user in users: if user == wanted: print("Found", wanted) breakelse: print(wanted, "not found")john not found
Nested loops
A loop inside a loop runs the inner loop completely for every pass of the outer one.
for row in range(1, 4): for col in range(1, 4): print(row * col, end="\t") print()1 2 3 2 4 6 3 6 9
Patterns are a classic exercise for nested loops:
rows = 4for i in range(1, rows + 1): print(" " * (rows - i) + "*" * (2 * i - 1))* *** ***** *******
Common loop patterns
prices = [120, 45, 300, 80, 45] total = 0 # accumulatefor p in prices: total += p count_cheap = 0 # count matchesfor p in prices: if p < 100: count_cheap += 1 biggest = prices[0] # track the maximumfor p in prices[1:]: if p > biggest: biggest = p print(total, count_cheap, biggest)print(sum(prices), sum(1 for p in prices if p < 100), max(prices)) # built-in shortcuts590 3 300 590 3 300
Write the loop yourself while learning, because interviewers and practice programs ask for it. In real code, prefer sum(), max(), min() and any() when they fit.
Check your understanding
Predict the output
total = 0for i in range(1, 10, 2): if i == 7: break total += iprint(total)9
range(1, 10, 2) gives 1, 3, 5, 7, 9. The loop adds 1, 3 and 5, then breaks at 7, so the total is 9.
Quick quiz
1. What numbers does range(3) produce?
range(n) starts at 0 and stops before n.
2. When does a loop’s else block run?
else is skipped if the loop was stopped by break.
3. What does continue do?
continue jumps straight to the next pass.
4. Which loop fits “keep asking until the user types quit”?
You do not know in advance how many times it will run, so use while.
Exercise: digits of a number
Use a while loop to print the sum of the digits of a number and the number reversed.
40721
Sum of digits: 14 Reversed: 12704
Hint 1
n % 10 gives the last digit and n // 10 removes it.
n = 40721digit_sum = 0reversed_n = 0 while n > 0: digit = n % 10 digit_sum += digit reversed_n = reversed_n * 10 + digit n //= 10 print("Sum of digits:", digit_sum)print("Reversed:", reversed_n)Sum of digits: 14 Reversed: 12704
Each pass peels off the last digit with % 10, adds it to the sum, appends it to reversed_n, then drops it with //= 10. The loop stops when no digits are left.
Program Practice
90 Python Loop Programs
Every program has a step-by-step explanation, colour-coded code and its real output.
Python loops FAQ
What is the difference between a for loop and a while loop?
A for loop goes through the items of a collection or a range, so the number of passes is known. A while loop repeats until its condition becomes false.
How do I loop with an index in Python?
Use enumerate(): for i, item in enumerate(items):. Avoid for i in range(len(items)) unless you really need the number alone.
How do I loop backwards in Python?
Use reversed(items) or range(start, stop, -1), for example for i in range(10, 0, -1):.
Does Python have a do-while loop?
No. Write while True: and break at the end of the body when the condition is met.