Python · Beginner
Loops in Python: for and while
In short: A for loop runs its block once for each item in a sequence such as a list, a string or a range(); a while loop repeats its block for as long as a condition stays true. Inside either loop, break leaves immediately and continue skips to the next round.
Repeating work
Loops let one block of code run many times, either once per item in a collection or until some condition changes. Python has two loop statements and they answer different questions.
for item in sequence: is the loop for "do this with each thing". Python takes the items one at a time, binds the loop variable to each in turn and runs the block. The sequence can be a list, a string (one character per round), a tuple, a range() or anything else iterable. You never manage an index or a counter yourself, which removes the most common source of off-by-one errors. When you do need numbers, range(n) produces 0 up to but not including n, range(a, b) produces a up to b, and range(a, b, step) counts in steps; range(1, 6) is 1, 2, 3, 4, 5. When you need both the position and the item, enumerate(sequence) yields pairs, and enumerate(sequence, start=1) counts from one.
while condition: is the loop for "keep going until". Before each round Python evaluates the condition; if it is true the block runs, then the condition is checked again. The block must eventually make the condition false, usually by changing a variable it depends on, or the loop never ends. A while fits situations where the number of rounds is unknown in advance: reading input until a sentinel word, retrying until something succeeds, halving a number until it drops below a limit.
Two statements change the flow inside a loop. break ends the loop at once and execution resumes after it. continue abandons the current round and goes straight to the next test or the next item. A loop may also carry an else: block, which runs when the loop finishes without hitting break; it is uncommon but occasionally the clearest way to say "nothing was found".
Choose for when you have a collection or a known count, while when you have a stopping condition. A while True: with a break inside is the idiom for loops whose exit test sits in the middle of the body.
Syntax
for item in sequence:
block
for i in range(start, stop, step): # stop is excluded
block
for index, item in enumerate(sequence, start=0):
block
while condition:
block # must eventually make condition false
break # leave the loop now
continue # skip to the next roundrange() with one argument starts at 0 and steps by 1. The loop variable keeps its last value after a for loop ends.
for versus while
| Question | Use |
|---|---|
| Do something with every item of a list, string or range | for |
| Repeat a known number of times | for with range() |
| Repeat until a condition changes | while |
| Read input until a sentinel line | while True with break |
| Need the position as well as the item | for with enumerate() |
for over a list, with enumerate and range
Four loops over a bus route, a range and a string.
stops = ["Harbour", "Market", "Station"]
for stop in stops:
print("Next stop:", stop)
for number, stop in enumerate(stops, start=1):
print(number, stop)
total = 0
for value in range(1, 6):
total += value
print("Sum of 1 to 5:", total)
for letter in "bus":
print(letter.upper(), end=" ")
print()Output
Next stop: Harbour Next stop: Market Next stop: Station 1 Harbour 2 Market 3 Station Sum of 1 to 5: 15 B U S
The first loop needs no index at all. enumerate supplies a running number alongside each item, unpacked into two loop variables. range(1, 6) stops before 6, so the sum is 1 + 2 + 3 + 4 + 5. A string is a sequence of characters, so the last loop visits each letter; end=" " makes print stay on the same line, and the bare print() finishes it.
while with a changing condition
A tank fills in rounds of 35 litres; then a number is halved until it reaches 1.
level = 0
rounds = 0
while level < 100:
level += 35
rounds += 1
print("Round", rounds, "level", level)
print("Full after", rounds, "rounds")
n = 40
while n > 1:
n //= 2
print("Ended with", n)Output
Round 1 level 35 Round 2 level 70 Round 3 level 105 Full after 3 rounds Ended with 1
Each round adds to level, moving it toward the exit condition; after three rounds level < 100 is false and the loop stops without running the block a fourth time. The second loop halves n (40, 20, 10, 5, 2, 1) until it is no longer greater than 1: the number of rounds depends on the data, which is exactly when while is the right tool.
break and continue while reading input
Readings arrive one per line until the word stop. The input is 12, -3, 8, stop, 20.
total = 0
kept = 0
while True:
line = input()
if line == "stop":
break
value = int(line)
if value < 0:
continue
total += value
kept += 1
print("Kept", kept, "readings, total", total)Input given to the program: 12 ↵ -3 ↵ 8 ↵ stop ↵ 20
Output
Kept 2 readings, total 20
The loop has no natural end condition, so it runs as while True and leaves through break when the sentinel arrives. Negative readings are skipped with continue, which jumps back to the top without touching total or kept. The 20 after stop is never read, because the loop had already ended.
Common mistakes
A while loop whose condition never changes
Why it goes wrong:
while count < 5:with no line that changescountruns forever, and the program appears to hang.Fix: Make sure something in the block moves toward the exit, or use for with range() when the count is known.
Python · fixcount = 0 while count < 5: print(count) count += 1Off-by-one with range()
Why it goes wrong:
range(1, 10)stops at 9 because the end value is excluded. A loop that should include the last number silently misses it.Fix: Add one to the end:
range(1, 11)for 1 through 10, or compute the bound from the data with len().Removing items from a list while looping over it
Why it goes wrong: Deleting shifts the later items left, so the loop skips the item that followed each deletion.
Fix: Build a new list of the items to keep, or loop over a copy.
Python · fixreadings = [3, -1, 4, -2] kept = [] for r in readings: if r >= 0: kept.append(r) print(kept) # [3, 4]Looping over indexes when you only need the items
Why it goes wrong:
for i in range(len(items)): print(items[i])works, but the index variable serves no purpose and invites mistakes.Fix: Loop over the items directly; use enumerate() when you need the position as well.
Where you use this
Almost every exercise on this site reads several lines of input, and a loop is how you read them. When the first line tells you how many follow, for _ in range(n) reads exactly that many. Once the values are in, another loop totals them, finds the largest, or prints a formatted row per item. The pattern of a variable updated inside a loop, an accumulator such as total or largest, is the shape behind averages, counts and sums in every language.
n = int(input())
largest = None
for _ in range(n):
value = int(input())
if largest is None or value > largest:
largest = value
print(largest)Key points
forvisits each item of a sequence;whilerepeats until a condition is false.range(a, b)counts from a up to b - 1;range(n)starts at 0.enumerate()gives index and item together; passstart=1to count from one.breakexits the loop;continueskips the rest of the current round.- A
whilebody must change something the condition depends on. - Never modify a list you are iterating over; build a new one instead.
Try it yourself
Read a number and print its times table from 1 to 5, one line per product, in the form 7 x 1 = 7. Use a for loop with range().
n = int(input())
# print n x 1 = ..., up to n x 5
77 x 1 = 7
7 x 2 = 14
7 x 3 = 21
7 x 4 = 28
7 x 5 = 35n = int(input())
for i in range(1, 6):
print(n, "x", i, "=", n * i)
Practise this
Related lessons
- Conditions: if, elif and else in PythonHow Python chooses between paths with if, elif and else, how truthiness works, why branch order matters, and how to write conditions that stay readable.8 min
- Lists in PythonHow Python lists store ordered, changeable collections: creating them, indexing and slicing, adding and removing items, sorting, copying and looping over them.9 min
- Functions in PythonHow to define and call Python functions with def, pass arguments, return results, use default and keyword arguments, and why variables inside are local.9 min
Frequently asked questions
How do I loop with an index in Python?
Use enumerate(): for i, item in enumerate(items): gives the position and the item on each round, starting from 0, or from any number you pass as start=. Looping over range(len(items)) and indexing by hand also works, but it is longer and easier to get wrong. Reach for the index only when you genuinely need it, for example to compare an item with its neighbour.
What does else do on a for or while loop?
The else block of a loop runs when the loop ends normally, that is, when the sequence is exhausted or the while condition becomes false, and is skipped when the loop is left by break. It suits search loops: put the "not found" message in else and break as soon as a match is found. The name confuses many readers, so a comment helps.
How do I loop over two lists at the same time?
zip(a, b) pairs the items up: for name, score in zip(names, scores): gives one item from each list per round and stops at the end of the shorter list. In Python 3.10 and later, zip(a, b, strict=True) raises an error if the lengths differ, which catches mismatched data early.
How this page was checked. Every program on it was run with CPython 3.11 at build time; runs in your browser on CPython 3.14 (Pyodide) by the publishing checks, and the output shown is what it printed. The Run buttons execute the same code on your device; nothing you type is sent anywhere.