A while loop repeats its body as long as the header expression is true. The language reference defines while that way and allows an optional else clause: that else runs when the condition becomes false without leaving the loop through break. When you already have a sequence to consume, a for loop is often clearer; use while when the stopping rule is computed each time.
Tested on: Python 3.13.3; kernel 6.14.0-37-generic.
What is a while loop in Python?
while keeps evaluating a condition; on each True result it runs the indented suite, then jumps back to the header. When the condition is False, execution continues after the loop (or runs the else block if you wrote one and no break fired). There is no built-in “count to N” form—you express repetition with the condition and whatever updates you place in the body.
Python while loop syntax
while condition:
body
else: # optional
suite # runs if loop finished without breakcondition can be any expression built from comparison and logical operators. The else clause is tied to completion without break, which surprises newcomers—see the dedicated section below.
Simple while loop example
count = 1
while count <= 3:
print(count)
count += 1You should see 1, 2, then 3 on separate lines.
If nothing in the body moves the state toward False, the header stays True forever. A counter must advance each pass—compare a stuck loop with a fixed version:
# BUG: n never changes — runs forever (do not leave running)
# n = 0
# while n < 3:
# print(n)n = 0
while n < 3:
print(n)
n += 1That prints 0, 1, then 2. The same idea applies when you read input or flip a flag: every iteration should make eventual exit possible.
Python while loop with user input
Interactive examples need a terminal; they are marked {run=false} so you can paste and run locally.
Keep asking until valid input
answer = ""
while answer.lower() not in ("y", "n"):
answer = input("Continue? [y/n]: ")
print("Thanks, got:", answer)Each pass re-reads until the user types y or n (case-insensitive check in the condition). The same yes/no pattern maps cleanly to if / else inside the loop body when you need different actions per answer.
Exit while loop when user enters 0
while True:
value = int(input("Enter a number (0 to quit): "))
if value == 0:
break
print("Twice:", value * 2)0 triggers break, which skips any while else and jumps after the loop.
Exit while loop when user enters q
while True:
text = input("Type text or q to quit: ")
if text.lower() == "q":
break
print(text.upper())Same pattern: infinite outer loop, explicit sentinel to break.
Infinite while loop in Python
A literal “run until I say stop” loop usually starts with while True and relies on break, a return, or an exception to end:
n = 0
while True:
n += 1
if n >= 3:
break
print("stopped at", n)You should see stopped at 3. while True is idiomatic when the real stop rule lives in the body (break, return, or exception).
Reach for a normal header when the stop rule is simple—static analyzers warn on while True that never breaks, returns, or raises. The counter pattern above is equivalent to:
n = 0
while n < 3:
print("tick", n)
n += 1Same finite work, but the condition advertises the exit upfront.
Python while loop with break
items = [1, 4, 9, 16]
idx = 0
while idx < len(items):
if items[idx] > 10:
print("first big:", items[idx])
break
idx += 1That prints first big: 16.
The header only decides whether to start another iteration; break leaves immediately and skips any while else. Compare a normal finish (else runs) with an early exit:
i = 0
while i < 2:
print("body", i)
i += 1
else:
print("else ran")
j = 0
while j < 2:
print("body", j)
break
else:
print("else skipped")You should see body 0, body 1, else ran, then body 0 only—no else line after break. Use break for exceptional exits; keep the main stop logic in the condition when readers can still see the guarantee at a glance.
Python while loop with continue
num = 0
while num < 5:
num += 1
if num % 2 == 0:
continue
print(num)You should see 1, 3, then 5—even values skip the print.
If continue runs before you advance state, the condition never changes and the loop can spin forever. The commented version below is a common bug pattern; the working version bumps num first:
# BUG: num can stay 0 forever — do not run unattended
# num = 0
# while num < 3:
# if num % 2 == 0:
# continue
# num += 1num = 0
while num < 3:
num += 1
if num % 2 == 0:
continue
print(num)That prints 1 and 3 without hanging.
Python while loop with multiple conditions
Use and in while condition
i, j = 1, 10
while i < 4 and j > 7:
print(i, j)
i += 1
j -= 1Both sides must stay true for another iteration.
Use or in while condition
or keeps the loop alive while any branch is true—use it when several independent reasons should continue processing.
x = -1
while x < 0 or x > 100:
x = 10
print("normalized:", x)The first pass sees x < 0; after assigning 10, both sides fail and the loop ends.
Use not in for multiple stop values
status = "pending"
allowed = {"done", "failed", "skipped"}
attempts = 0
while status not in allowed and attempts < 3:
attempts += 1
status = "done"
print(status)status leaves the loop once it enters allowed or attempts cap out—membership keeps multiple terminal states readable.
Python while loop with else
When while else runs
The else suite runs after the loop condition becomes false normally (no break).
numbers = [1, 3, 5, 9]
idx = 0
while idx < len(numbers):
if numbers[idx] % 2 == 0:
print("found even", numbers[idx])
break
idx += 1
else:
print("No even number found")That prints No even number found for the given list.
When while else does not run
If break runs, the else suite is skipped—even if the loop condition was still true at that moment:
numbers = [1, 4, 9]
idx = 0
while idx < len(numbers):
if numbers[idx] % 2 == 0:
print("found even", numbers[idx])
break
idx += 1
else:
print("No even number found")That prints found even 4 only; the else branch never runs because break left the loop early.
Nested while loop in Python
Basic nested while loop syntax
row = 0
while row < 2:
col = 0
while col < 2:
print(row, col)
col += 1
row += 1You should see four row col pairs from (0, 0) through (1, 1). Reset the inner loop variable before re-entering the inner while.
User enters 0 to exit loop
Outer loop waits for work; inner loop drains a counter; typing 0 (here simulated with next on a list) exits the outer loop entirely—same pattern as while True plus if value == 0: break, but nested:
inputs = iter([2, 3, 0]) # pretend user typed 2, then 3, then 0
def read_int():
return next(inputs)
while True:
n = read_int()
if n == 0:
print("outer: done")
break
while n > 0:
print(" inner:", n)
n -= 1You should see inner ticks for 2 and 3, then outer: done. With a real CLI, replace read_int() with int(input(...)) and the same if n == 0: break guard.
Common mistakes with Python while loops
- Forgetting to update variables used in the condition, causing infinite spins.
- Placing
continuebefore the counter or input refresh, freezing progress. - Expecting
whileelseto run afterbreak—it does not. - Using
whilewhen aforloop over a sequence would be simpler and safer. - Off-by-one with manual indexes—consider
for index, value in enumerate(data)when you need positions. - Copy-pasting interactive
inputloops without a guaranteed exit path.
Python while loop quick reference table
| Goal | Pattern |
|---|---|
| Counted repetition | while i < n: … i += 1 |
| Sentinel exit | while True: … if sentinel: break |
| Skip iteration | if skip: continue (after advancing state) |
| Multiple tests | while cond_a and cond_b: |
| Membership stop | while value not in finished: |
| Run if no break | while …: … else: … |
Summary
while repeats on a Boolean condition; keep each iteration moving toward False or use a deliberate break. continue skips the rest of the body but must not skip progress updates. Combine tests with and, or, or not in when several facts gate the loop. The optional else runs only on natural completion—never after break. Nested while loops need clear inner resets; interactive flows should always offer a sentinel such as 0 or q. Reach for a for loop when you are walking a collection instead of waiting on a dynamic rule.

