By WebNest Studio Engineering Team
Python Tutorial
Loops in Python: for and while
Loops repeat work: process every order, retry until a download succeeds, read every line of a file. Python has two loop statements. The for loop iterates over the items of any iterable — lists, strings, ranges, dictionaries, files. The while loop repeats as long as a condition stays true.
This lesson covers both loops, range(), enumerate() and zip(), looping over dictionaries, nested loops, the loop else clause, and how to choose between for and while.
Why it matters
Python's for loop goes through the items of a collection directly, without index arithmetic, and enumerate and zip cover the cases where you need a position or two lists at once. Using them is what makes code look like Python and not like another language translated word for word.
The for Loop
for item in iterable: runs the block once per item. It works with any iterable, not just numbers. range(stop), range(start, stop) and range(start, stop, step) produce integer sequences (stop is exclusive). enumerate() gives index and item together; zip() walks several sequences in parallel; reversed() and sorted() change the order.
The while Loop
while condition: repeats while the condition is truthy. Use it when you do not know in advance how many iterations are needed: reading until the user types "quit", retrying a network call, running a game loop. Make sure something inside the loop eventually makes the condition false, or you get an infinite loop.
Loop else
A loop can have an else block that runs only if the loop finished without a break. It is handy for search loops: "look for the item; else report it was not found".
for vs while
Use for when iterating over a collection or a known range — it cannot accidentally run forever and needs no manual counter. Use while for condition-driven repetition. Most Python loops are for loops; if you write while i < len(items) with a manual index, a for loop is almost always cleaner.
Examples
for loops with range, enumerate and zip
for i in range(1, 6):
print(i, end=" ")
print()
for n in range(10, 0, -3):
print(n, end=" ")
print()
fruits = ["mango", "apple", "banana"]
for index, fruit in enumerate(fruits, start=1):
print(index, fruit)
names = ["Asha", "Ravi", "Meera"]
scores = [88, 72, 95]
for name, score in zip(names, scores):
print(f"{name}: {score}")
1 2 3 4 5
10 7 4 1
1 mango
2 apple
3 banana
Asha: 88
Ravi: 72
Meera: 95
Looping over strings and dictionaries, and nested loops
for ch in "Hi!":
print(ch)
prices = {"pen": 10, "book": 250, "bag": 899}
for item, price in prices.items():
print(f"{item:<5} Rs.{price}")
for row in range(1, 4):
print(" ".join(str(row * col) for col in range(1, 4)))
H
i
!
pen Rs.10
book Rs.250
bag Rs.899
1 2 3
2 4 6
3 6 9
while loops and the loop else clause
balance = 1000
years = 0
while balance < 2000:
balance *= 1.08
years += 1
print(f"Doubled in {years} years: {balance:.2f}")
numbers = [4, 8, 15, 16, 23, 42]
target = 15
for position, n in enumerate(numbers):
if n == target:
print("Found at index", position)
break
else:
print("Not found")
for n in numbers:
if n == 99:
break
else:
print("99 not found (loop finished without break)")
Doubled in 10 years: 2158.92
Found at index 2
99 not found (loop finished without break)
Common Mistakes
- Forgetting that range(1, 10) stops at 9.
- Modifying a list while iterating over it — iterate over a copy or build a new list.
- Writing while loops whose condition never becomes false.
- Using range(len(items)) and items[i] when enumerate() is clearer.
- Misunderstanding loop else: it runs when no break happened, not when the loop body never ran.
Exercise
Print each student's position, name and score. Use enumerate for the position and zip to pair each name with its score.
Expected output: 1. Asha - 82 then 2. Ravi - 91
names = ["Asha", "Ravi"]
scores = [82, 91]
# TODO: loop over the names and scores together, with a position starting at 1
Show hints
zip(names, scores)yields pairs such as("Asha", 82).enumerate(..., start=1)adds a counter. Unpack withfor position, (name, score) in ....
Show solution
names = ["Asha", "Ravi"]
scores = [82, 91]
for position, (name, score) in enumerate(zip(names, scores), start=1):
print(f"{position}. {name} - {score}")
Quick quiz
1. Which numbers does range(2, 10, 3) produce?
- A. 2, 5, 8, 11
- B. 2, 3, 4
- C. 3, 6, 9
- D. 2, 5, 8
Show answer
D. It starts at 2 and adds 3 each time, stopping before 10.
2. When does the else block of a loop run?
- A. When the loop finishes without reaching a break
- B. When the loop body raises an error
- C. Every time round the loop
- D. Only when the loop never runs
Show answer
A. It is skipped only when the loop is ended by break.
3. What does zip([1, 2, 3], ["a", "b"]) yield?
- A. Three pairs, the last with None
- B. Two pairs; it stops at the shorter input
- C. An error
- D. Five single items
Show answer
B. zip stops as soon as one of its inputs runs out.
Interview questions
Why is enumerate() preferred over range(len(items))?
Show answer
enumerate(items) gives the index and the item together, so the loop body does not need to look the item up with items[i]. It is shorter, harder to get wrong, and works with any iterable, including ones that have no length or cannot be indexed.
What is the use of the else clause on a loop?
Show answer
It runs when the loop ends normally and is skipped when the loop is left with break. The typical use is a search: the loop breaks when the item is found, and the else block handles the case where it was not found, without needing a separate flag variable.
Key Points to Remember
- for iterates over any iterable; range() generates number sequences (stop exclusive).
- enumerate() gives indices, zip() pairs sequences, .items() walks dicts.
- while repeats while a condition is true — ensure it eventually ends.
- A loop's else runs only if the loop was not ended by break.
- Prefer for loops for collections; while for condition-driven repetition.
Practice in the playground
Write and run your own code for this topic, or start from the exercise or an example. Runs Python in your browser. Your code for each topic is kept in this browser.
Run the examples
Change an input, predict the result, then compare it with the output. Explain why the result changes.
Written by
WebNest Studio Engineering Team
Practical lessons from developers working with Java, Python, React, databases and production systems.
Led by Vansh Duggal, Founder, WebNest Studio · Full-stack & software engineering