Ad – 728Γ—90
πŸ”€ Control Flow

Python While Loop – Repeat Until a Condition Is False

The while loop is Python's tool for repeating code as long as a condition remains true. Unlike a for loop which iterates over a sequence, a while loop keeps going until something changes. It's perfect for user input validation, game loops, server polling, and any situation where you don't know in advance how many iterations you need.

⏱️ 20 min read 🎯 Beginner πŸ“… Updated 2026

While Loop Syntax

The basic structure of a Python while loop is:

Python
while condition:
    # Code to execute while condition is True
    # IMPORTANT: Something here must eventually make condition False

The loop checks the condition before each iteration. If the condition is False from the start, the loop body never runs. If the condition never becomes False, the loop runs forever (an infinite loop).

Basic While Loop Examples

Counting with While

Python
# Count from 1 to 5
count = 1

while count <= 5:
    print(f"Count: {count}")
    count += 1  # Without this, the loop would run forever!

print("Done!")
β–Ά Output
Count: 1 Count: 2 Count: 3 Count: 4 Count: 5 Done!

Every element has a role:

  • count = 1 β€” Initialize the counter before the loop
  • while count <= 5 β€” Check the condition
  • count += 1 β€” Update the counter to avoid an infinite loop

Countdown Timer

Python
countdown = 10

while countdown > 0:
    print(f"T-minus {countdown}...")
    countdown -= 1

print("πŸš€ Liftoff!")
β–Ά Output
T-minus 10... T-minus 9... T-minus 8... ... T-minus 1... πŸš€ Liftoff!

While Loop for User Input Validation

One of the most common real-world uses of while is validating user input β€” keep asking until you get a valid answer:

Python
# Keep asking until a valid age is entered
age = -1  # Initialize with an invalid value

while age < 0 or age > 120:
    age_input = input("Enter your age (0-120): ")

    if age_input.isdigit():
        age = int(age_input)
        if age < 0 or age > 120:
            print("Age must be between 0 and 120.")
    else:
        print("Please enter a valid number.")

print(f"Your age is: {age}")
Ad – 336Γ—280

While-Else Clause

Python's while loop has an optional else clause that runs when the condition becomes False (but NOT when the loop is exited with break):

Python
# Search for a number with while-else
target = 7
num = 1

while num <= 10:
    if num == target:
        print(f"Found {target}!")
        break
    num += 1
else:
    # Only runs if loop completed WITHOUT break
    print(f"{target} not found in range 1-10")

# Another example: login attempts
attempts = 0
max_attempts = 3
password = "secret123"

while attempts < max_attempts:
    guess = input("Enter password: ")
    attempts += 1

    if guess == password:
        print("Access granted!")
        break
else:
    print("Too many failed attempts. Account locked.")

Infinite Loops with Break

Sometimes you intentionally create an infinite loop (while True) and exit it with break when a condition is met. This is common in menus, game loops, and server applications:

Python
# A simple command-line menu
while True:
    print("\n--- Menu ---")
    print("1. Say Hello")
    print("2. Add Numbers")
    print("3. Exit")

    choice = input("Enter choice (1-3): ")

    if choice == "1":
        name = input("Your name: ")
        print(f"Hello, {name}!")
    elif choice == "2":
        a = float(input("First number: "))
        b = float(input("Second number: "))
        print(f"Sum: {a + b}")
    elif choice == "3":
        print("Goodbye!")
        break
    else:
        print("Invalid choice. Try again.")

Nested While Loops

Python
# Multiplication table using nested while
row = 1

while row <= 5:
    col = 1
    while col <= 5:
        print(f"{row * col:3}", end="")
        col += 1
    print()  # New line after each row
    row += 1
β–Ά Output
1 2 3 4 5 2 4 6 8 10 3 6 9 12 15 4 8 12 16 20 5 10 15 20 25

For Loop vs While Loop

FeatureFor LoopWhile Loop
When to useKnown number of iterations or iterating a sequenceUnknown iterations, condition-based
Typical useIterating lists, ranges, stringsUser input, game loops, polling
Infinite loop riskVery lowHigher (easy to forget update)
Counter managementAutomaticManual
ReadabilityMore readable for sequencesMore readable for conditions

Common Mistakes

Mistake 1: Forgetting to Update the Condition Variable

Python
# ❌ INFINITE LOOP - never terminates!
x = 0
while x < 5:
    print(x)
    # Missing: x += 1

# βœ… Correct
x = 0
while x < 5:
    print(x)
    x += 1
🚨
How to Stop an Infinite Loop

If your program gets stuck in an infinite loop, press Ctrl+C in the terminal to send a KeyboardInterrupt and stop execution.

Mistake 2: Off-by-One Errors

Python
# Want to print 1 through 10
i = 1
while i < 10:    # ❌ Stops at 9, not 10
    print(i)
    i += 1

i = 1
while i <= 10:   # βœ… Correctly goes to 10
    print(i)
    i += 1

πŸ‹οΈ Practical Exercise

  1. Write a while loop that prints all even numbers from 2 to 20.
  2. Write a program that sums numbers entered by a user until they enter 0.
  3. Create a simple guessing game: pick a number 1-10, let the user guess until correct, tell them if their guess is too high or too low.

πŸ”₯ Challenge Exercise

Build a text-based ATM simulator using while loops. The account starts with $1000. The menu should have: Check Balance, Deposit, Withdraw, and Exit. Validate that withdrawals don't exceed the balance. Count and display total transactions when exiting.

Interview Questions

  • What is the difference between a for loop and a while loop in Python?
  • What happens if a while loop condition never becomes False?
  • What does the else clause in a while loop do?
  • When would you use while True with break instead of a regular condition?
  • How do you avoid infinite loops when writing while loops?
  • What is the difference between break and continue in a while loop?

πŸ“‹ Summary

  • A while loop repeats code as long as its condition is True.
  • Always ensure something inside the loop will eventually make the condition False.
  • The optional else clause runs when the condition becomes False (not when broken out with break).
  • while True creates an intentional infinite loop β€” use break to exit.
  • Use while when you don't know in advance how many iterations are needed.
  • Press Ctrl+C to interrupt an accidentally infinite loop.

FAQ

Can a while loop iterate over a list? +

Yes, using an index counter: i = 0; while i < len(my_list): ... i += 1. But a for loop is much more readable for this purpose. Use for loops to iterate collections, and while loops for condition-based repetition.

What is the do-while equivalent in Python? +

Python doesn't have a do-while loop. The closest equivalent is while True: ... if condition: break. This guarantees the loop body runs at least once before checking the exit condition.

How can I add a delay inside a while loop? +

Use time.sleep(seconds) from the time module: import time; time.sleep(1) pauses for 1 second. This is commonly used in polling loops that check for new data at intervals.