while

Updated March 16, 2026 · Keywords
keyword loop iteration control-flow

The while keyword in Python executes a block of code repeatedly as long as a condition evaluates to True. It’s useful when you don’t know in advance how many iterations you’ll need.

Syntax

while condition:
    # Loop body

Basic Examples

Simple Counter

count = 0

while count < 3:
    print(count)
    count += 1
# Output:
# 0
# 1
# 2

User Input Loop

password = ""

while password != "secret":
    password = input("Enter password: ")

print("Access granted")

Reading Until Condition Met

numbers = [1, 2, 3, 4, 5]
total = 0
index = 0

while index < len(numbers):
    total += numbers[index]
    index += 1

print(total)
# Output: 15

The else Clause

Python’s while loops can have an else block that runs when the condition becomes False:

count = 0

while count < 3:
    print(count)
    count += 1
else:
    print("Loop finished!")
# Output:
# 0
# 1
# 2
# Loop finished!

The else block does not run if you exit the loop with break:

count = 0

while count < 3:
    if count == 2:
        break
    print(count)
    count += 1
else:
    print("Loop finished!")
# Output:
# 0
# 1

Breaking and Continuing

break - Exit Loop Early

number = 0

while True:
    print(number)
    number += 1
    if number >= 3:
        break
# Output:
# 0
# 1
# 2

continue - Skip to Next Iteration

count = 0

while count < 5:
    count += 1
    if count == 3:
        continue
    print(count)
# Output:
# 1
# 2
# 4
# 5

Infinite Loops

Use while True for loops that run until explicitly broken:

while True:
    response = input("Type 'quit' to exit: ")
    if response == "quit":
        break
    print(f"You typed: {response}")

Be careful with infinite loops — always provide a way to break out!

Practical Patterns

Processing Until Sentinel Value

total = 0

while True:
    value = input("Enter number (or 'done'): ")
    if value == "done":
        break
    total += int(value)

print(f"Total: {total}")

Simulating do-while

Python doesn’t have a built-in do-while, but you can simulate it:

while True:
    result = get_user_input()
    if is_valid(result):
        break

Waiting for Condition

import time

while not is_network_available():
    print("Waiting for network...")
    time.sleep(1)

print("Connected!")

While vs For

SituationUse
Known number of iterationsfor
Unknown iterations, condition-basedwhile
Iterating over a sequencefor
Waiting for external state changewhile

Common Mistakes

Forgetting to Update the Condition

# Bug: infinite loop
while count < 3:
    print(count)
    # Missing: count += 1

Off-by-One Errors

# Check your condition carefully
i = 0
while i <= 3:  # Runs 4 times (0,1,2,3)
    print(i)
    i += 1

See Also