Python loops: for and while, with practical examples

A loop in Python repeats a block of code instead of asking you to write the same lines again. A for loop repeats over a known set of items, such as names in a list or numbers from a range. A while loop repeats while a test stays true, and it stops as soon as that test becomes false.
The choice between them comes down to what you know before the loop starts. If you know the items, or you know how many times to repeat, for is the clearer choice. If you know only the stopping condition, such as a total reaching a target, while fits better. The examples below show both patterns, and they show the two most common loop errors: a loop that runs one time too many, and a loop that never stops.
Repeat over items with for
The simplest for loop uses a list of names. Python takes the first name, stores it in the loop variable, runs the indented block, then moves to the next name. When no names remain, the loop ends and the program continues with the lines after the block. The loop variable is an ordinary variable, so after the loop it holds the last item it was given, which is a detail worth knowing when you print it later by accident.
names = ["Sara", "Ali", "Maya"]
for name in names:
print("Hello,", name)
A for loop can also build a result as it goes. The total example below starts at zero, then adds each price in turn. After the loop, the total holds the sum. This accumulate pattern shows up in many programs, from adding scores to counting items that pass a test, and it is a good pattern to practise until it feels natural.
prices = [10, 20, 15]
total = 0
for price in prices:
total = total + price
print(total)
Repeat a set number of times with range
When you need a loop to run a set number of times, range gives you the numbers to loop over. Range with one argument starts at zero and stops before that argument, so range with 5 gives five numbers starting at zero. That stopping rule is the source of the classic off by one error, where a loop runs one time too few or one time too many because the end value was treated as included.
for number in range(5):
print(number)
for number in range(1, 6):
print(number)
for number in range(0, 10, 2):
print(number)
numbers = [3, 8, 11, 20]
for number in numbers:
if number % 2 == 0:
print(number)
Repeat until a test fails with while
A while loop is for cases where the number of repetitions is not known in advance. The countdown below starts at 3, prints the count, subtracts 1, and repeats while the count is greater than zero. Each run changes the tested value, so the test eventually becomes false and the loop stops. Without that subtraction, the count would stay at 3 forever and the loop would never end.
count = 3
while count > 0:
print(count)
count = count - 1
print("Done")
Stop early or skip one item
Break ends a loop at once, and continue skips the rest of the current run and moves to the next item. Break is useful when you have found what you were looking for and the remaining items no longer matter. Continue is useful when one item should be skipped, such as an empty value in a list, while the rest should still be processed. Both change the flow inside the loop, so use them sparingly and keep the reason visible in the code.
names = ["Sara", "Ali", "Maya"]
for name in names:
if name == "Ali":
break
print(name)
for number in [1, 2, 3, 4]:
if number == 3:
continue
print(number)
The first loop prints only Sara, because it breaks when it reaches Ali. The second loop prints 1, 2, and 4, because it skips 3 and continues with the next number. If a loop body grows long, a break or continue buried in the middle can be hard to spot, so keep loop bodies short, or move the body into a function with a clear name. That keeps the loop itself easy to read, and the details live in one named place.
| Loop form | Use it when | Watch out for |
|---|---|---|
| for over a list | You have items to visit one by one | Changing the list while looping over it |
| for with range | You need a set number of repetitions | Range stops before its end value |
| while | You know the stopping test, not the count | A tested value that never changes inside the loop |
Common mistakes to watch for
An infinite while loop is the most serious loop mistake, because the program keeps running and prints the same output again and again. Stop the program with the interrupt key for your system, then look for the line that should change the tested value. If that line is missing, or if it is outside the loop by indentation, add it inside the loop and test again with a small limit. Testing a while loop with a small starting value first makes an infinite loop obvious quickly, before it runs for a long time.
Off by one errors come from treating range as inclusive at the end. Range with 5 does not include 5, and range from 1 to 5 does not include 5 either. When a loop should include the end value, add 1 to the end argument, and print the range values once to confirm. That one check prevents a whole class of errors in counting, indexing, and pagination code later on.
Changing a list while looping over it is a subtler mistake. Removing or adding items during a loop can skip items or visit items twice, because the loop is tracking positions while the list changes under it. The safe approach is to build a new list inside the loop, or to loop over a copy, and then replace the original after the loop ends. That rule is worth learning early, even if the examples here do not need it yet.
Forgetting the colon, or indenting the block inconsistently, breaks a loop in the same way it breaks a condition. The if and else guide on this site covers those errors in detail, and the same fixes apply here: add the colon, and keep indentation consistent with spaces. A loop body that is not indented at all is not part of the loop, so it runs once instead of repeating, which can look like a loop that does nothing.
Limits of this guide
This guide covers for and while loops, range, break, and continue for simple sequences. It does not cover looping over dictionaries in detail, nested loops for grids, or generator functions that produce values one at a time. Those topics build on the patterns here, and they are easier to learn once the basic loop forms are solid. This guide also does not cover performance tuning for very large loops, which depends on the data and the machine in ways a beginner guide cannot usefully generalise.
Worked example: total and average from a list
A loop over a list of numbers is a common first real use of for, because it turns a list into a result step by step. The example below adds each score to a running total, counts the items as it goes, and then works out the average after the loop ends. The running total starts at zero before the loop, which matters, because each pass adds to the value left by the previous pass.
scores = [12, 18, 15, 20]
total = 0
for score in scores:
total = total + score
average = total / len(scores)
print("Total:", total)
print("Average:", average)
Trace the loop by hand for the first two passes. Before the loop, total is 0. On the first pass, score is 12, so total becomes 12. On the second pass, score is 18, so total becomes 30. Continuing that way gives 45 after the third pass and 65 after the fourth, and the average line then divides 65 by 4. Hand tracing a short loop like this builds trust in the code before it grows longer.
Notice that the average line sits outside the loop, at the same indent as the for line. Indent decides what repeats, so a line inside the loop runs once per item, while a line outside runs once in total. Moving the average line inside the loop by mistake would print an average after every item, which is a different program even though the words are the same.
For and while, side by side
For and while answer different questions, and the table below keeps the distinction plain. A for loop suits a known set of items or a known count, because it steps through them one by one. A while loop suits a condition that must be checked again after each pass, such as waiting for valid input or repeating until a value reaches a target.
| Question | For loop | While loop |
|---|---|---|
| What repeats? | Each item in a sequence | While a test stays true |
| When does it stop? | When items run out | When the test becomes false |
| Main risk | Wrong indent for lines after the loop | A test that never becomes false |
| Typical use | Totals, lists, printed rows | Input checks, countdowns, retries |
A while loop needs a step inside it that moves the test toward false, or it will run forever. A countdown that subtracts one each pass moves toward its stop value, while a loop that never changes its test value has no way out. When a loop seems to hang, the first check is whether the variable in the test changes inside the loop body.
Choosing between the two loops is easier with a simple question. If the items are already known, for is the direct choice. If the stopping point depends on something that happens during the loop, such as a reader typing a correct value, while is the direct choice. Either loop can be forced to do the other job, yet the direct choice is easier to read and to debug.
Break, continue, and the else clause on a loop
Break stops a loop at once, and continue skips the rest of the current pass and moves to the next item. Both are useful in small doses. Break suits a search that can stop once the item is found, because later items cannot change the answer. Continue suits a pass that should skip items that do not qualify, such as skipping blank lines while reading a list of names.
names = ["", "Maya", "", "Ali"]
for name in names:
if name == "":
continue
print(name)
Python loops also accept an else clause, which runs when the loop ends without hitting break. That clause suits a search that must report when nothing was found. A loop that breaks on a match skips the else part, while a loop that runs through all items without a match runs it. The else clause on a loop is easy to misread at first, so a comment explaining its job helps a future reader.
Overusing break and continue makes a loop harder to follow, because the reader must track several exits. A loop with one clear exit, such as running through all items or stopping on a found item, is easier to trace. When a loop needs several breaks, it may be a sign that the loop body should become a function that returns as soon as the answer is known.
Nested loops and a small grid example
A loop inside another loop runs the inner loop fully for each pass of the outer loop. That pattern builds rows and columns, such as a multiplication table or a grid of coordinates. The example below prints pairs for two short ranges, and the count of printed lines is the product of the two range sizes, which is why nested loops grow quickly.
for row in range(3):
for col in range(3):
print(row, col)
Trace the first few lines to see the pattern. When row is 0, col runs through 0, 1, and 2, printing three pairs. Then row becomes 1, and col runs through 0, 1, and 2 again. The outer variable changes slowly, the inner variable changes fast, and that rhythm is the key to reading any nested loop.
Nested loops deserve care with names, because reusing the same variable name for both loops overwrites the outer value and breaks the pattern. Give each loop its own clear name, such as row and col, and keep the inner body short. When the inner body grows long, moving it into a function with a clear name keeps the loop structure visible at a glance.
Frequently asked questions
How do I choose between for and while?
Use for when you know what to repeat over, such as items in a list or a set number of times. Use while when the loop must keep going until a condition changes, such as waiting for valid input or a total to reach a target.
What stops a while loop that never ends?
A change inside the loop that makes its test false. If no line inside the loop changes the tested value, the test stays true and the loop keeps running. Add a counter or a flag update inside the loop, and test it with a small limit first.
Can a loop run zero times?
Yes. A for loop over an empty list runs zero times, and a while loop whose test is false at the start also runs zero times. That is normal, and it is why code after a loop must not assume the loop body ran at least once.
Can I change a list while looping over it?
Changing a list during a loop can skip items or repeat them, because the loop position shifts as items move. Loop over a copy of the list when items must be removed, or build a new list with the items to keep.
How do I loop over two lists at the same time?
Use the zip function, which pairs items from two sequences position by position and stops at the shorter one. That pairing keeps the code short, and it avoids tracking two indexes by hand.
Does a loop else clause run after break?
No, the else clause on a loop runs only when the loop ends without hitting break. That makes it useful for reporting that a search found nothing, because a break on a match skips it.


