Python Loops, For vs While, With Examples You Can Run
A Python for loop takes items from an iterable, such as a list, string, or range; a while loop repeats while its condition is true. Use for i in range(5) for the values 0 through 4, and a while loop for a condition-controlled task such as asking for input until it is valid. Both support break, continue, and a loop else clause.
On this page▾
- The for loop: when you know what you're iterating over
- Using range() to loop a specific number of times
- The while loop: when you don't know how many times you'll repeat
- break and continue: controlling a loop from the inside
- The loop's own else clause
- When should you use for and while loops in Python?
- Frequently asked questions
- What is the difference between a for loop and a while loop in Python?
- Can both while and for loops use break and continue?
- When does a Python loop else run?
| Construct | Behavior |
|---|---|
for |
Takes successive items from an iterable |
while |
Repeats while its condition is true |
break |
Exits the innermost loop |
continue |
Skips the rest of the current iteration |
Loop else |
Runs on normal completion, not after break |
The for loop: when you know what you're iterating over
A for loop in Python is different from the "count from 1 to 10" style loop you may have seen described in other languages. The official tutorial explains: "Python's for statement iterates over the items of any sequence (a list or a string), in the order that they appear in the sequence." You are not managing a counter yourself; you are handing Python a collection and letting it walk through each item.
words = ['cat', 'window', 'defenestrate']
for w in words:
print(w, len(w))
Running this prints each word followed by its length: cat 3, window 6, defenestrate 12. There is no manual counter variable anywhere in this code; Python handles the iteration itself.
Dictionaries, which loops often walk through, are covered in Python Dictionaries Explained With Simple Examples.
Using range() to loop a specific number of times
When you do want the classic "repeat this N times" behavior, Python's built-in range() function generates exactly the sequence of numbers you need:
for i in range(5):
print(i)
This prints 0, 1, 2, 3, 4, one per line. The official tutorial is specific about the boundary: "The given end point is never part of the generated sequence," so range(5) produces five values (0 through 4), not six. Give range() a starting point and a step when needed:
print(list(range(5, 10))) # [5, 6, 7, 8, 9]
print(list(range(0, 10, 3))) # [0, 3, 6, 9]
The while loop: when you don't know how many times you'll repeat
A while loop repeats as long as a condition stays true, which makes it the right tool when you do not know in advance how many iterations you will need, for example repeatedly asking a user for input until they give you something valid.
count = 5
while count > 0:
print(count)
count -= 1
print("done")
This prints 5, 4, 3, 2, 1, then "done." The loop keeps running as long as count > 0 stays true, and stops the moment that condition becomes false. Unlike a for loop over a known sequence, nothing here tells Python in advance how many times the loop will run; it is entirely determined by the condition.
break and continue: controlling a loop from the inside
Both loop types support two keywords for changing their normal behavior mid-loop. The official tutorial defines break as exiting "the innermost enclosing for or while loop" immediately, and continue as moving straight to "the next iteration of the loop" without running the rest of the current iteration's code.
for n in range(2, 10):
for x in range(2, n):
if n % x == 0:
print(f"{n} equals {x} * {n // x}")
break
Run this and you will see output like 4 equals 2 * 2, 6 equals 2 * 3, 8 equals 2 * 4, 9 equals 3 * 3. As soon as the inner loop finds any number x that divides evenly into n, it prints the factorization and immediately exits the inner loop with break, rather than continuing to check the remaining values of x.
for num in range(2, 10):
if num % 2 == 0:
print(f"Found an even number {num}")
continue
print(f"Found an odd number {num}")
This prints one line for every number 2 through 9. When num is even, continue skips straight to the next number without running the final print line in that same iteration, which is why each even number only gets one line of output, not two.
The loop's own else clause
Python allows a for or while loop to have its own else clause, which runs when a for exhausts its iterable or a while condition becomes false. A break, return, or raised exception skips the loop’s else. The official tutorial's own example uses this to detect prime numbers:
for n in range(2, 10):
for x in range(2, n):
if n % x == 0:
print(n, 'equals', x, '*', n // x)
break
else:
print(n, 'is a prime number')
Running this prints "2 is a prime number," "3 is a prime number," "4 equals 2 * 2," "5 is a prime number," "6 equals 2 * 3," "7 is a prime number," "8 equals 2 * 4," and "9 equals 3 * 3." The else block only runs for the numbers where the inner loop never found a factor and so never hit break, which is exactly the definition of a prime number. The official tutorial notes a key detail: this else belongs to the for loop, not to the if statement nested inside it, an indentation distinction that determines which block runs.
When should you use for and while loops in Python?
- Use a
forloop when you are iterating over an iterable (such as a list, string, range, or generator). You do not have to know its length in advance. - Use a
whileloop when the stopping condition depends on something that happens during the loop itself, like user input, a calculation result, or an external event, and you cannot know the number of iterations ahead of time. - Use
breakto exit a loop early once you have found what you were looking for, avoiding unnecessary additional iterations. - Use
continueto skip the rest of the current iteration's code without exiting the whole loop.
Frequently asked questions
What is the difference between a for loop and a while loop in Python?
A for loop retrieves successive items from an iterable; a while loop tests a condition before each iteration. A while loop may run zero times if its condition is false at the start.
Can both while and for loops use break and continue?
Yes. break exits the innermost loop, while continue skips the remaining body of that iteration. A while loop then tests its condition again; a for loop advances to the next item.
When does a Python loop else run?
After a for loop exhausts its iterable or a while condition becomes false, including when the loop body never ran. It is skipped if break, return, or an exception exits the loop.
Sources
About this guide
Howlane operator · Checked against the official sources listed above. It is general information, not professional advice.
AboutEditorial standardsCorrectionsReport an error
Edit history
- Updated
- Updated
- Updated
- Updated
- Published