Tutorials Python Python while Loop
Ch 16 / 58
Python Beginner 9 min read Chapter 16 of 58

Python while Loop

The while loop keeps running as long as a condition is True — making it the right tool whenever you don't know in advance how many iterations are needed. From input validation and game loops to server polling and retry logic, while loops power any process that must continue until a goal is reached. This chapter covers everything: basic syntax, counter and flag patterns, infinite loops with break, continue, the while...else clause, and the do-while simulation pattern.

What you'll learn in this chapter
while loop syntax, condition and body
Counter, accumulator, flag and sentinel patterns
Infinite loops and safe exit with break
break, continue and the while...else clause
Do-while simulation and input validation
for vs while — when to use each
Advertisement

What is a while Loop?

A while loop repeatedly executes its body as long as its condition evaluates to True. Unlike a for loop — which iterates over a fixed sequence — a while loop continues until a state change makes the condition false. This makes it the right choice when you genuinely don't know the iteration count in advance.

Every while loop needs three things to avoid running forever: a condition to check, a body to execute, and something inside the body that eventually changes the condition to False. Forgetting the third element creates an infinite loop.

Pre-condition loop Python checks the condition before each iteration. If it's False on the very first check, the body never runs at all — zero iterations.
Condition-driven
Runs while condition is True
Unknown count
Iterations not known upfront
Infinite risk
Must change the condition!
Event loops
Servers, games, polling

Basic Syntax & How It Works

The while statement is followed by a condition and a colon. The indented block below runs repeatedly until the condition becomes False. The most common pattern uses a counter variable that increments each iteration.

Python — while_basic.py
# Syntax: while condition:
#             body  (indented 4 spaces)

# Count 1 to 5
count = 1                # ① initialise
while count <= 5:        # ② check condition
    print(count)           # ③ execute body
    count += 1            # ④ update (essential!)
# 1  2  3  4  5

# Count DOWN — Rocket launch!
n = 5
while n > 0:
    print(n, end=" ")
    n -= 1
print("Blast off! 🚀")
# 5 4 3 2 1 Blast off! 🚀

# Condition False at start — body NEVER runs
x = 10
while x < 0:
    print("Never printed")

# While with a computed condition
balance = 100.0
steps   = 0
while balance > 1:
    balance *= 0.9
    steps   += 1
print(f"Reached ≤1 in {steps} steps") # 44 steps
while condition:
The condition is re-evaluated before every iteration. The colon and 4-space indent are mandatory — same rules as if.
count += 1
The update step is critical. Without it, count never changes, the condition stays True forever, and you have an infinite loop.
while False:
If the condition is False at the very start, the body is skipped entirely — zero iterations occur.

Common while Loop Patterns

Four patterns appear in almost every Python program that uses while: the counter loop, the accumulator loop, the flag-controlled loop, and the sentinel loop. Recognising these patterns makes it easy to write — and debug — any while loop.

Python — while_patterns.py
# ── Pattern 1: Counter loop ─────────────────────────
val = 1
while val < 1000:
    print(val, end=" ")
    val *= 2
# 1 2 4 8 16 32 64 128 256 512

# ── Pattern 2: Accumulator loop ─────────────────────
number = 1234
total  = 0
while number > 0:
    total  += number % 10   # add last digit
    number //= 10           # remove last digit
print(f"Digit sum: {total}")  # 10

# Factorial
n, result = 6, 1
while n > 0:
    result *= n
    n      -= 1
print(f"6! = {result}")      # 6! = 720

# ── Pattern 3: Flag-controlled loop ─────────────────
import random
found    = False
attempts = 0
while not found:
    roll     = random.randint(1, 6)
    attempts += 1
    if roll == 6:
        found = True
print(f"Rolled 6 after {attempts} tries")

# ── Pattern 4: Sentinel loop ─────────────────────────
# Read values until a sentinel is entered
numbers = []
while True:
    raw = input("Enter number (or 'done'): ")
    if raw == "done":
        break
    numbers.append(int(raw))
print(f"You entered: {numbers}")
Advertisement
K2infocom Python Masterclass & Backend Development
Master Python, Django & Backend APIs with AI
Go from absolute beginner to building production-ready REST APIs, web applications, and ML pipelines. Real projects, live mentoring in Vadodara, and placement support included.
2,400+
Students Enrolled
4.9 ⭐
Google Rating
6 Months
Full Program
100%
Placement Support
Python 3 Django & DRF FastAPI PostgreSQL Machine Learning Docker & AWS Real Projects AI Tools

Infinite Loops — while True & Safe Exits

An infinite loop runs forever because its condition never becomes False. While accidental infinite loops are bugs, intentional while True: loops are a common and idiomatic pattern — used for interactive menus, game loops, server listeners, and input validation. You exit them explicitly with break.

Python — infinite_loops.py
# ❌ Accidental infinite loop — update is missing
x = 1
# while x > 0:
#     print(x)   ← never decrements, loops forever!

# ✅ Intentional — interactive menu
while True:
    print("\n1. Start  2. Settings  3. Quit")
    choice = input("Choose: ")
    if choice == "1":
        print("Starting...")
    elif choice == "2":
        print("Settings...")
    elif choice == "3":
        print("Goodbye! 👋")
        break             # ← explicit exit
    else:
        print("Invalid choice.")

# ✅ Input validation — do-while simulation
while True:
    age_str = input("Enter age (1-120): ")
    try:
        age = int(age_str)
        if 1 <= age <= 120:
            break         # valid — exit loop
        print("Age must be 1–120.")
    except ValueError:
        print("Please enter a number.")
print(f"Valid age: {age}")

# ✅ Retry with limit
MAX     = 5
retries = 0
while True:
    if retries >= MAX:
        print("Max retries reached.")
        break
    retries += 1
    print(f"Attempt {retries}...")
Stopping an infinite loop Press Ctrl + C in a terminal to send KeyboardInterrupt and stop execution. In Jupyter Notebook click the stop (■) button.

break and continue in while Loops

break exits the loop immediately; continue skips the remaining body and jumps back to the condition check. Both work identically in while and for loops, but in a while loop you must be especially careful to update the counter before any continue.

Python — while_break_continue.py
# break — exit the while loop immediately
n = 0
while True:
    n += 1
    if n >= 5:
        break
    print(n, end=" ")    # 1 2 3 4
print()

# break — search and stop
target, num = 7, 0
while num < 100:
    num += 1
    if num == target:
        print(f"Found {target}!")
        break

# continue — skip current iteration
i = 0
while i < 10:
    i += 1               # ← update BEFORE continue!
    if i % 2 == 0:
        continue         # skip even numbers
    print(i, end=" ")    # 1 3 5 7 9
print()

# continue — skip invalid/empty data
data  = [5, 0, 8, 0, 3, 6]
idx   = 0
total = 0
while idx < len(data):
    val = data[idx]
    idx += 1             # ← always update first
    if val == 0:
        continue         # skip zeros
    total += val
print(f"Sum (no zeros): {total}")  # 22

# ⚠️ DANGER: update AFTER continue → infinite loop!
# i = 0
# while i < 5:
#     if i == 3: continue  ← i stuck at 3 forever
#     i += 1               ← never reached
Statement Effect Loop else runs?
break Exits the loop immediately No — skipped
continue Skips rest of current iteration, re-checks condition
Yes (if loop finishes)
pass Does nothing — placeholder
Yes (normal flow)

while...else Clause & Do-While Simulation

Python's while loop supports an else clause — it runs when the loop's condition becomes False naturally, but is skipped if the loop exits via break. Python also has no built-in do-while, but while True: ... if condition: break provides identical behaviour.

Python — while_else_dowhile.py
# while...else — else runs if condition becomes False
n = 1
while n <= 5:
    print(n, end=" ")
    n += 1
else:
    print("\nLoop finished normally")
# 1 2 3 4 5
# Loop finished normally

# else SKIPPED when break exits
n = 1
while n <= 5:
    if n == 3: break
    print(n, end=" ")
    n += 1
else:
    print("SKIPPED")     # never printed
# 1 2  (else block skipped)

# Retry loop — report success OR exhausted
import random
attempts = 0
while attempts < 3:
    ok = random.random() > 0.6
    attempts += 1
    if ok:
        print(f"✅ Success on attempt {attempts}")
        break
    print(f"Attempt {attempts} failed...")
else:
    print("❌ All 3 attempts failed")

# Do-while simulation — body runs at LEAST once
while True:
    pw = input("Password (min 8 chars): ")
    if len(pw) >= 8:
        break
    print("Too short, try again.")
print("Password accepted! ✅")

for vs while — When to Use Each

Both loops can solve many of the same problems, but choosing the right one makes code more readable and less error-prone. The core rule: use for when you know what to iterate over; use while when you're waiting for a condition to change.

Scenario Prefer Why
Iterate over a list, string, or tuple for Direct, no counter needed
Repeat exactly N times for + range() Intent is clear
Unknown number of iterations while Loop until a condition changes
Input validation — repeat until valid while True Run at least once, exit on valid input
Game loop / event loop / server while True Run forever until exit signal
Read a file line by line for Files are iterable
Retry until success or max attempts while Condition depends on external result
Python — for_vs_while.py
# ✅ Use for — iterating a known sequence
for fruit in ["apple", "banana", "cherry"]:
    print(fruit)

# ✅ Use while — condition depends on runtime state
balance = 1000
while balance > 0:
    print(f"Balance: ₹{balance}")
    balance -= int(input("Withdraw: ₹"))

# Both can count 1–5; for is cleaner
for i in range(1, 6):           # ✅ prefer for
    print(i, end=" ")

i = 1
while i <= 5:                   # works, more verbose
    print(i, end=" ")
    i += 1

Practice Python Online — Free Compilers

Don't want to install anything yet? Practice all while loop examples from this chapter directly in your browser with these free Python environments.

▶
Online Python 3 Compiler
Write, run and debug Python code in your browser. No installation required. Test every while loop example instantly.
Open Compiler
Replit
Full IDE online
Google Colab
Free GPU notebooks
JupyterLite
Notebooks in browser
Programiz
Beginner-friendly
Chapter Summary
  • The while loop runs its body as long as the condition is truthy — it checks the condition before every iteration (pre-condition loop).
  • Every while loop needs: initialisation, a condition, and an update inside the body. Missing the update creates an infinite loop.
  • Key patterns: counter loop, accumulator loop, flag-controlled loop, and sentinel loop (read until a stop value).
  • Intentional infinite loops (while True:) are idiomatic — use them for menus, game loops, and input validation. Exit with break.
  • break exits immediately; continue skips rest of current iteration and re-checks condition. Always update the counter before continue.
  • The while...else clause runs only when the condition becomes False naturally — skipped when break exits. Use it for retry / search patterns.
  • Python has no do-while. Simulate with while True: body; if condition: break — body runs at least once.
  • Use for for known sequences; use while when the number of iterations depends on runtime state.
⚡
Free Resource
Download our Python while Loop Cheat Sheet
Syntax, loop patterns, infinite loops, break/continue, while-else & do-while simulation — one printable page.
Get Sheet
Advertisement
Quick Check — Test Your Understanding
Question & Answer
✓ Answer

Every while loop needs:

  • Initialisation — a variable set before the loop that the condition depends on (e.g. count = 0).
  • Condition — the expression evaluated before each iteration (e.g. while count < 10:).
  • Update — a statement inside the body that changes the variable so the condition eventually becomes False (e.g. count += 1). Without this, the condition never changes and the loop runs forever.
✓ Answer

The else block attached to a while loop executes when the loop's condition becomes False naturally — the loop completed all iterations without being interrupted by break. If break exits the loop, the else block is skipped entirely.

n = 3
while n > 0:
    n -= 1
else:
    print("Done")  # prints — no break occurred

Typical use: retry loops where you want to signal "all retries exhausted" when the else runs.

✓ Answer

Python has no do-while statement. A do-while guarantees the body executes at least once. In Python, use while True: with a break at the point where the condition would be checked:

while True:
    answer = input("Yes or No? ")
    if answer in ("yes", "no"):
        break
    print("Invalid. Try again.")

The body always runs at least once because the condition is never checked before the first execution.

✓ Answer

When continue is reached, Python immediately jumps back to the condition check — skipping all remaining code in the body. If the counter update (i += 1) appears after continue, it gets skipped too, meaning the counter never advances and the loop runs forever:

# ❌ Infinite loop — i stuck at 3
i = 0
while i < 5:
    if i == 3: continue  # i never updates!
    i += 1

# ✅ Fixed — update first
while i < 5:
    i += 1                  # update before continue
    if i == 3: continue
✓ Answer

Use while when the number of iterations is not known in advance and depends on a runtime condition:

  • Input validation — repeat until the user provides valid input.
  • Event loops / game loops — keep running until the user chooses to quit.
  • Retry logic — attempt an operation until it succeeds or a limit is reached.
  • Sentinel loops — read data until a sentinel value is received.
  • Mathematical convergence — iterate until a value falls within a tolerance.

If you know exactly what to iterate over (a list, file, or fixed range), prefer for — cleaner and less error-prone.

MCQ 1 of 3
How many times does the body of while 5 < 3: print("hi") execute?
MCQ 2 of 3
In a while...else structure, when is the else block skipped?
MCQ 3 of 3
What is the output of: i=0; while i<4: i+=1; print(i, end=" ")?

Rate Us on Google

4.8 / 5
Enjoying this tutorial?
Your 5-star review helps other learners discover our free tutorials and encourages us to keep creating quality content.
80+ reviews
Write a Google Review
Join WhatsApp Channel