Introduction & Syntax
Loops · Study material
Loops repeat work: process every student in a list, read input until the user types "done", draw a pattern, search for a prime. Python has two loops – for, which walks through the items of any iterable, and while, which repeats as long as a condition holds – plus break, continue and an unusual else clause. Placement tests love loop questions: how many times does it run, what is the loop variable afterwards, what happens if you remove items while iterating? This topic answers all of them with runnable examples, then 50 practice questions run on Python 3.
On this page
- for loops and range()
- while loops
- break, continue and pass
- The else clause of a loop
- enumerate(), zip(), reversed(), sorted() and dict.items()
- Nested loops, patterns, and changing a list while looping
The for loop
A Python for loop is a "for each" loop: for item in iterable: binds item to each element in turn. It works on lists, strings, tuples, sets, dictionaries, files and ranges alike – there is no C-style for (i = 0; i < n; i++).
# for walks through the items of ANY iterable: list, string, tuple, dict, file …
for city in ["Pune", "Delhi", "Kochi"]:
print("Visiting", city)
for ch in "Hi!":
print(ch, end=" ")
print()
total = 0
for price in (120, 80, 45.5):
total += price
print("Total:", total)
Visiting Pune Visiting Delhi Visiting Kochi H i ! Total: 245.5
range(): counting loops
range(stop), range(start, stop) and range(start, stop, step) produce integers from start up to but not including stop. A negative step counts down. range is lazy – range(10**9) uses almost no memory – yet supports len(), indexing and in. Its arguments must be ints, and step cannot be 0.
print(list(range(5))) # 0 … 4: stop is EXCLUDED
print(list(range(2, 8))) # start, stop
print(list(range(1, 20, 5))) # start, stop, step
print(list(range(10, 0, -3))) # counting down: negative step
print(list(range(5, 0))) # empty: cannot reach 0 going up
print(len(range(0, 100, 7)), range(0, 100, 7)[3]) # range is a lazy sequence
[0, 1, 2, 3, 4] [2, 3, 4, 5, 6, 7] [1, 6, 11, 16] [10, 7, 4, 1] [] 15 21
The while loop
while condition: checks the condition before every pass. Something inside the loop must eventually make it false, or the loop never ends. Use while when you do not know how many passes are needed – reading input, waiting for a target, processing digits.
# while repeats as long as the condition is true – use it when the number of steps is not known in advance
balance, years = 10_000, 0
while balance < 20_000:
balance *= 1.08 # 8% interest per year
years += 1
print(f"Doubled after {years} years: {balance:.2f}")
# A digit-reversing loop
n, reverse = 1208, 0
while n:
reverse = reverse * 10 + n % 10
n //= 10
print(reverse)
Doubled after 10 years: 21589.25 8021
break, continue and pass
break exits the innermost loop at once; continue skips to the next pass; pass does nothing. After a for loop ends, the loop variable keeps its last value – loops do not create a scope.
for n in range(1, 10):
if n == 7:
break # leave the loop completely
if n % 2 == 0:
continue # skip the rest of this pass, go to the next n
print(n, end=" ")
print()
for n in range(3):
pass # a placeholder: does nothing
print("pass left n at", n)
1 3 5 pass left n at 2
The else clause of a loop
Both for and while may have an else block. It runs when the loop ends normally – the iterable is exhausted or the while condition becomes false – and is skipped when the loop ends with break. Think of it as "no break": perfect for searches.
def first_multiple_of_7(numbers):
for n in numbers:
if n % 7 == 0:
print("Found", n)
break
else: # runs only if the loop finished WITHOUT break
print("No multiple of 7 in", numbers)
first_multiple_of_7([3, 10, 14, 21])
first_multiple_of_7([1, 2, 3])
# Prime test with for-else
for n in [11, 15]:
for d in range(2, int(n ** 0.5) + 1):
if n % d == 0:
print(n, "is not prime")
break
else:
print(n, "is prime")
Found 14 No multiple of 7 in [1, 2, 3] 11 is prime 15 is not prime
enumerate(), zip(), reversed() and dictionaries
Instead of for i in range(len(names)), use enumerate(names) to get index and item together. zip(a, b) walks several sequences in step and stops at the shortest. reversed() and sorted() iterate in another order without modifying the original. Looping over a dict gives its keys; use .items() for key–value pairs and .values() for values.
names = ["Asha", "Ravi", "Meera"]
marks = [91, 78, 85]
for i, name in enumerate(names, start=1): # index and item together
print(i, name)
for name, m in zip(names, marks): # walk two sequences in step
print(f"{name}: {m}")
for name in reversed(names): # backwards without changing the list
print(name, end=" ")
print()
for name, m in sorted(zip(names, marks), key=lambda pair: pair[1], reverse=True):
print(name, m, end=" | ")
print()
prices = {"tea": 20, "coffee": 35}
for item, price in prices.items(): # keys and values of a dict
print(item, price)
1 Asha 2 Ravi 3 Meera Asha: 91 Ravi: 78 Meera: 85 Meera Ravi Asha Asha 91 | Meera 85 | Ravi 78 | tea 20 coffee 35
Nested loops and patterns
For every pass of the outer loop the inner loop runs to completion, so the body runs rows × columns times. Patterns use the outer variable to decide what the inner loop (or string multiplication) prints. A break leaves only the inner loop.
# Nested loops: the inner loop runs completely for every pass of the outer loop
for row in range(1, 4):
for col in range(1, 5):
print(f"{row * col:3}", end="")
print() # newline after each row
# A pattern: the row number decides how many stars
for i in range(1, 5):
print(" " * (4 - i) + "*" * (2 * i - 1))
1 2 3 4 2 4 6 8 3 6 9 12 * *** ***** *******
Do not change a list while looping over it
A for loop over a list walks an internal index. Removing an item shifts the later items left, so the loop skips the next one – a classic bug. Build a new list instead (a list comprehension) or loop over a copy. Changing the size of a dict or set during iteration raises RuntimeError.
nums = [2, 4, 6, 7, 8]
for n in nums: # ✘ removing items shifts the rest, so one is skipped
if n % 2 == 0:
nums.remove(n)
print(nums)
nums = [2, 4, 6, 7, 8]
odds = [n for n in nums if n % 2 != 0] # ✔ build a new list
print(odds)
nums = [2, 4, 6, 7, 8]
for n in nums[:]: # ✔ or iterate over a COPY
if n % 2 == 0:
nums.remove(n)
print(nums)
[4, 7] [7] [7]
Common mistakes
- Off-by-one with range –
range(1, 10)stops at 9. - Infinite while loops – the condition never becomes false.
- Resetting an accumulator inside the loop –
total = 0belongs before it. - for i in 10: – an int is not iterable; use
range(10). - Removing items while iterating – some are skipped.
- Assigning to the loop variable – does not change the list or the next value.
- else on the if inside the loop instead of on the loop.
Key points to remember
- for iterates over items; range(start, stop, step) excludes stop.
- while checks its condition before every pass.
- break exits, continue skips, pass does nothing.
- A loop's else runs only when no break happened.
- The loop variable keeps its last value after the loop.
- Use enumerate() for indexes and zip() for parallel lists.
- Never change a list's size while iterating it.
Frequently asked questions
Does Python have a do-while loop?
No. Use while True: with a break at the end of the body, so the body always runs at least once.
How do I break out of two nested loops?
Put the loops in a function and return, use a flag checked by the outer loop, or use for-else with continue/break.
Is for i in range(len(lst)) wrong?
It works, but enumerate(lst) is clearer and avoids indexing errors. Use range(len(…)) only when you truly need positions alone.
Where can I learn more?
Read Python for Loop, Python while Loop and Python Loop Patterns in the Python tutorial, then practise with the exercises below.