While Loop In Python — PBA Institute Tutorial
Chapter 06 · Python Programming Series
12 min read Beginner

Conditional Repetition With The While Loop

The Python while loop is the natural choice when you don't know in advance how many times a block must repeat. It keeps running while a condition is true — perfect for menu-driven apps, retry logic, polling sensors, or any code that must wait for something to happen.

Overview

Wait Until

Repeat as long as a condition is true — no need to know the count up-front.

🔁

Retry Logic

Re-attempt network calls or user prompts until success.

🕹️

Game Loops

Run frame-by-frame logic until the player quits.

📡

Polling

Check sensors or queues continuously in background services.

📋

Menu Systems

Show options repeatedly until the user chooses to exit.

Syntax

  • Syntax: while condition: followed by an indented body.
  • Modify the condition's variables inside the body so the loop can eventually stop.
  • while True: creates an intentional infinite loop — exit it with break.
  • Python has no built-in do-while; emulate it with while True: + break.
While Loop — Syntax
# basic while
while condition:
    # body

# intentional infinite loop
while True:
    cmd = input("> ")
    if cmd == "quit":
        break

# do-while equivalent
while True:
    value = compute()
    if not value:
        break

Detailed Explanation

  • How it works: Python evaluates the condition at the top of every iteration. If it is true, the body executes; otherwise control jumps past the loop. The condition is evaluated before the body — if it is false initially, the body never runs.
  • Updating the loop variable: Beginners often forget to mutate the variable that controls the condition, creating an infinite loop. Always plan how the loop will terminate before writing the body.
  • Infinite loops on purpose: Servers, game loops, and CLI menus often write while True: and rely on break, return, or an exception to exit. This is idiomatic and not a bug.
  • Sentinel-controlled loops: Read input until a special 'sentinel' value is encountered — e.g. read numbers until the user types -1. Sentinels make the stopping rule explicit.
  • Loop-else clause: Just like for, a while may have an else block that runs when the condition becomes false without a break.
  • Performance: while is slightly slower than for over the same number of iterations because each iteration re-evaluates the condition expression. Prefer for for fixed-size loops.

Code Examples

Example 1 — Print Numbers 1 to 5
i = 1
while i <= 5:
    print(i)
    i += 1
Output 1
2
3
4
5
Example 2 — Sum Until User Stops
total = 0
while True:
    n = int(input("Number (0 to stop): "))
    if n == 0:
        break
    total += n
print("Total:", total)
Output Number (0 to stop): 5
Number (0 to stop): 3
Number (0 to stop): 0
Total: 8
Example 3 — Login Retry
pwd = ""
attempts = 3
while attempts > 0 and pwd != "secret":
    pwd = input("Password: ")
    attempts -= 1
print("Welcome!" if pwd == "secret" else "Locked out")
Output Password: hello
Password: secret
Welcome!
Example 4 — Reverse a Number
n = 1234
rev = 0
while n > 0:
    rev = rev * 10 + n % 10
    n //= 10
print("Reversed:", rev)
Output Reversed: 4321
Example 5 — Menu Driven Calculator
while True:
    print("1.Add 2.Sub 3.Quit")
    choice = input("> ")
    if choice == "3":
        print("Bye"); break
    a = int(input("a: ")); b = int(input("b: "))
    print(a+b if choice=="1" else a-b)
Output 1.Add 2.Sub 3.Quit
> 1
a: 4 b: 3 → 7
> 3
Bye
Example 6 — while-else: Find Factor
n = 17
d = 2
while d * d <= n:
    if n % d == 0:
        print(n, "is composite"); break
    d += 1
else:
    print(n, "is prime")
Output 17 is prime

Real-World Use Cases

Servers

An HTTP server's accept-loop is essentially a while-True running forever.

Retry Mechanisms

Re-attempt a failed API call with exponential back-off until it succeeds.

Sensor Polling

Read environmental sensors every few seconds until a threshold is hit.

Job Queues

Workers loop forever, pulling tasks from a queue and processing them.

Game Engines

Each frame runs a while-loop that processes input, updates state, and renders.

Chat Clients

Continuously read incoming messages until the user disconnects.

Notes & Pro Tips

  • Initialise loop variables before the while statement.
  • Always ensure the condition can become false — otherwise you'll loop forever.
  • Use while True: + break when the exit condition is complex.
  • Add a maximum-attempts counter to retry loops to avoid hanging indefinitely.
  • Use time.sleep() inside polling loops to avoid 100% CPU usage.
  • Test edge cases: zero iterations, single iteration, and termination conditions.

Common Mistakes

  • Infinite loop: forgetting to update the counter inside the body.
  • Off-by-one: using < instead of <= (or vice versa).
  • Wrong condition order: while True: with no break hangs.
  • Heavy work inside the condition: the condition is re-evaluated every iteration.
  • Mutating the wrong variable: updating a different name leaves the condition unchanged.
  • Tight CPU loops: a polling loop without sleep can pin a CPU core to 100%.

Practice Problems

  • Problem 1: Compute the sum of digits of a positive integer using a while loop.
  • Problem 2: Read numbers until -1 is entered and print the average of all entered values.
  • Problem 3: Use a while loop to compute the GCD of two numbers (Euclidean algorithm).
  • Problem 4: Print the Fibonacci series up to a given limit n.
  • Problem 5: Build a password-strength prompt that keeps asking until the user enters a strong one.
  • Problem 6: Simulate a simple ATM with options for deposit, withdraw, balance, and exit.

Interview Questions

  • Q1. When should you prefer while over for?
  • Q2. How do you simulate a do-while loop in Python?
  • Q3. What is an infinite loop and how is it used in practice?
  • Q4. Explain the loop-else clause with a while example.
  • Q5. How can you avoid 100% CPU usage in a continuous polling loop?
  • Q6. How do you implement retry logic with a maximum number of attempts?

Frequently Asked Questions

  • Q1: Is while True considered bad practice?
    Not at all. Many production servers and CLIs use while True with a break or return on the exit condition. It is clear and idiomatic.
  • Q2: Does Python have a do-while loop?
    No. Emulate it using while True: ... if not condition: break.
  • Q3: Why does my while loop never stop?
    Likely the variable in the condition is not updated inside the body. Add a print statement to debug.
  • Q4: Can a while loop have an else?
    Yes — it runs when the condition becomes false naturally (no break).
  • Q5: How do I exit a nested while?
    Use a flag variable, wrap them in a function and return, or raise an exception.
  • Q6: Is while faster than for?
    Usually for is slightly faster for fixed iteration counts. Use the loop that expresses your intent most clearly.

Summary

The while loop is your tool for repetition with dynamic stopping conditions. From retry mechanisms to game tick loops to server event loops, it powers the most resilient parts of real systems. Combine it with break, continue, sentinels, and timeouts to write loops that always terminate safely and behave gracefully even when the world is unpredictable.

Continue Learning

Previous

Go to Previous Chapter

Next

Go to Next Chapter