Python While Loop Examples

Learn Python while loop with simple examples, including syntax, counter loops, user input, break, continue, while else, nested while loops, and multiple conditions.

Published

Updated

Read time 8 min read

Reviewed byDeepak Prasad

Python While Loop Examples

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

text
while condition:
    body
else:          # optional
    suite      # runs if loop finished without break

condition 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

python
count = 1
while count <= 3:
    print(count)
    count += 1
Output

You 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:

python
# BUG: n never changes — runs forever (do not leave running)
# n = 0
# while n < 3:
#     print(n)
python
n = 0
while n < 3:
    print(n)
    n += 1
Output

That 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

python
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

python
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

python
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:

python
n = 0
while True:
    n += 1
    if n >= 3:
        break
print("stopped at", n)
Output

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:

python
n = 0
while n < 3:
    print("tick", n)
    n += 1
Output

Same finite work, but the condition advertises the exit upfront.


Python while loop with break

python
items = [1, 4, 9, 16]
idx = 0
while idx < len(items):
    if items[idx] > 10:
        print("first big:", items[idx])
        break
    idx += 1
Output

That 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:

python
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")
Output

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

python
num = 0
while num < 5:
    num += 1
    if num % 2 == 0:
        continue
    print(num)
Output

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:

python
# BUG: num can stay 0 forever — do not run unattended
# num = 0
# while num < 3:
#     if num % 2 == 0:
#         continue
#     num += 1
python
num = 0
while num < 3:
    num += 1
    if num % 2 == 0:
        continue
    print(num)
Output

That prints 1 and 3 without hanging.


Python while loop with multiple conditions

Use and in while condition

python
i, j = 1, 10
while i < 4 and j > 7:
    print(i, j)
    i += 1
    j -= 1
Output

Both 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.

python
x = -1
while x < 0 or x > 100:
    x = 10

print("normalized:", x)
Output

The first pass sees x < 0; after assigning 10, both sides fail and the loop ends.

Use not in for multiple stop values

python
status = "pending"
allowed = {"done", "failed", "skipped"}
attempts = 0
while status not in allowed and attempts < 3:
    attempts += 1
    status = "done"

print(status)
Output

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).

python
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")
Output

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:

python
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")
Output

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

python
row = 0
while row < 2:
    col = 0
    while col < 2:
        print(row, col)
        col += 1
    row += 1
Output

You 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:

python
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 -= 1
Output

You 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 continue before the counter or input refresh, freezing progress.
  • Expecting while else to run after break—it does not.
  • Using while when a for loop 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 input loops 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.


References


Frequently Asked Questions

1. When does the optional else on a while loop run?

It runs after the loop condition becomes false in the normal way; if the loop exits with break, the else suite is skipped.

2. What is the difference between while and for in Python?

A for loop iterates over a known sequence; a while loop re-evaluates a condition each time and fits open-ended repetition—see the Python for loop tutorial when you have a collection to walk.

3. Why does my while loop run forever?

The condition never becomes false—check that something inside the body advances state toward termination or use break with a clear guard.

4. Can I combine multiple tests in the while header?

Yes—combine boolean expressions with and, or, or membership tests such as value not in stop_set.
Deepak Prasad

R&D Engineer

Founder of GoLinuxCloud with more than 15 years of expertise in Linux, Python, Go, Laravel, DevOps, Kubernetes, Git, Shell scripting, OpenShift, AWS, Networking, and Security. With extensive …