Python loops repeat a block of code: a for loop handles each value supplied by an iterable, while a while loop continues as long as a condition is true. Use for to process items or a known range of values; use while when repetition should end after some state changes. Understanding what advances each loop makes it easier to trace iterations and avoid infinite loops and off-by-one errors.
How does a for loop work in Python?
A for loop asks an iterable—such as a list or string—for its values one at a time. For each value, Python assigns it to the loop variable and runs the indented body. When there are no more values, the loop ends.
As an Amazon Associate I earn from qualifying purchases.
names = ["Ada", "Grace", "Linus"]
for name in names:
print(name)
The passes are: first, name is "Ada"; next, it is "Grace"; finally, it is "Linus". Python then reaches the end of the list and stops. The loop is driven by the iterable’s values, not by an automatic numeric counter.
Crashes, No Sound, or Screen Glitches?
Random freezes, missing sound and display glitches usually trace back to one bad driver. Find and replace yours safely.Free scan · under a minutePC Slower Than It Used to Be?
A free scan shows the junk files, broken settings and background clutter dragging Windows down - then fixes them in one click.Free scan · Windows 10 & 11These explanatory examples follow the behavior described in the Python 3.14.8 tutorial on control flow.
#1 Best Overall
Use range() for a sequence of numbers
range() represents an immutable arithmetic sequence. Its stop value is excluded, which means range(5) supplies 0, 1, 2, 3, and 4—not 5.
for number in range(1, 4):
print(number) # 1, 2, 3
With two arguments, the first is the start and the second is the excluded stop. Add a third argument to set the step:
for number in range(2, 9, 2):
print(number) # 2, 4, 6, 8
Because the stop is excluded, check the endpoints when a loop appears to run one time too few or too many.
Do these 3 things before closing this tab:
1Scan for outdated or missing drivers - takes under a minute2Clear out junk files and repair common Windows errors3Fix the driver behind crashes, sound loss and screen glitchesWhen do you need an index?
If you need both a value and its position, use enumerate() rather than managing a separate counter:
Rank #2
for index, name in enumerate(names):
print(index, name)
Use range(len(items)) only when the index itself is needed for an operation. If you only need each item, iterate over the items directly; it is clearer and avoids unnecessary indexing.
When should you use for versus while?
| Loop | What drives another pass | How it ends | Typical use |
|---|---|---|---|
for |
The next value from an iterable | The iterable runs out of values | Processing a collection or a known sequence of values |
while |
A Boolean condition that remains true | The condition becomes false | Repeating until an event or state change |
Choose based on what determines the next pass. A list of prices naturally calls for for; a prompt that should continue until the user enters a valid response naturally calls for while.
Trace a while loop
remaining = 3
while remaining > 0:
print(remaining)
remaining -= 1
On the first pass, remaining is 3; after printing, it becomes 2. On the second pass it prints 2, then becomes 1. The third pass prints 1 and changes the value to 0. The next condition check is false, so the loop ends.
Recommended Free Tools
The update is essential: if the condition stays true and nothing changes the state it depends on, the loop may never terminate. Decide what will eventually make the condition false, and update that state inside the loop.
How do break, continue, and loop else work?
break stops the current loop
break exits the innermost enclosing loop immediately. In this search, Python prints Found when it reaches Grace and does not inspect Linus:
for name in names:
if name == "Grace":
print("Found")
break
In nested loops, a break exits only the innermost loop—not every loop around it.
continue skips the rest of this pass
continue skips the remaining statements in the current pass and moves to the next item or condition check. For example, this prints only positive values:
values = [3, 0, -2, 5]
for value in values:
if value <= 0:
continue
print(value)
Loop else means no break occurred
A loop’s optional else suite runs when a for loop exhausts its iterable or a while condition becomes false. It does not run if the loop exits through break. The else is aligned with the loop, not with an if inside it.
target = "Grace"
for name in names:
if name == target:
print("Found")
break
else:
print("Not found")
When the target is Grace, the loop breaks and the else is skipped. If the target is absent, the loop reaches the end of names normally and prints Not found.
How can you use loops in small projects?
Add up receipt prices
Keep a running total and add each price as the loop visits it:
prices = [2.50, 3.25, 1.75]
total = 0
for price in prices:
total += price
print(f"Total: ${total:.2f}")
The first pass changes total from 0 to 2.50; the second adds 3.25, making 5.75; the third makes it 7.50. The formatted output is Total: $7.50.
Count words
Split a sentence on whitespace, then update a dictionary once for each word:
Best Value
sentence = "loops make work repeat"
counts = {}
for word in sentence.split():
counts[word] = counts.get(word, 0) + 1
print(counts)
The first two passes add "loops": 1 and "make": 1. Later passes add "work": 1 and "repeat": 1. If a word appears again, its existing count increases.
Build a filtered list
When keeping only items that meet a condition, create a new list instead of removing values from the list being traversed:
numbers = [1, 2, 3, 4, 5]
evens = []
for number in numbers:
if number % 2 == 0:
evens.append(number)
print(evens) # [2, 4]
The first value, 1, is not added; the second, 2, is. The loop continues over the original list while building evens. If you need to modify a collection during traversal, iterating over a copy is another option. Changing the collection being traversed can lead to surprising logic.
Make a guessing loop end clearly
A guessing game can use while because it repeats until the player’s input matches the answer or the player quits. Validate input and provide a clear exit path:
secret = 7
while True:
response = input("Guess 1–10, or type q to quit: ").strip().lower()
if response == "q":
print("Goodbye")
break
if not response.isdigit():
print("Enter a whole number or q.")
continue
guess = int(response)
if not 1 <= guess <= 10:
print("Choose a number from 1 to 10.")
continue
if guess == secret:
print("Correct")
break
print("Try again")
For a guess of 4, the loop prints Try again and asks again; a later guess of 7 prints Correct and breaks. Typing q also exits. Non-numeric and out-of-range entries do not end the game; continue returns to the prompt.
Quick Recap
What loop mistakes should you watch for?
- Including the stop value:
range(start, stop)excludesstop. Adjust the endpoint only when the desired sequence actually includes that number. - Forgetting to change a
whilecondition: update the counter or other relevant state, or provide a deliberate exit such asbreak. - Expecting
breakto leave every nested loop: it exits only the innermost enclosing loop. - Indenting loop
elseas if it belonged to anif: align it with the loop; it describes normal loop completion withoutbreak. - Removing items from a collection as you iterate over it: use a copy or build a separate collection to avoid skipping or mishandling values.
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.




