Codectionary / Developer documentation / Python

while

The while loop repeats a block of code as long as its condition remains True. Unlike a for loop, which iterates a known number of times over a sequence, a while loop is ideal when you don't know in advance how many iterations you'll need - like waiting for valid user input or running until some external condition changes. A while loop can also have an optional else clause that runs if the loop finishes normally, without hitting a break.

Syntax

while condition:\n    # code to repeat

Examples

Basic While Loop

Repeating a block of code until a counter condition becomes False.

count = 0

while count < 5:
    print(count)
    count += 1

print("Done")

While Loop with break

Using while True with break to create a loop that exits based on internal logic rather than a simple counter.

attempts = 0

while True:
    attempts += 1
    guess = attempts  # simulate a guess
    if guess == 3:
        print(f"Found it after {attempts} attempts")
        break

Input Validation Loop

A very common real-world use: repeat until the user provides valid input.

while True:
    age_input = input("Enter your age: ")
    if age_input.isdigit():
        age = int(age_input)
        break
    print("Please enter a valid number")

print(f"Age accepted: {age}")

While with else

The else block runs only if the loop completes without hitting a break.

numbers = [1, 3, 5, 7]
target = 4
i = 0

while i < len(numbers):
    if numbers[i] == target:
        print("Found!")
        break
    i += 1
else:
    print("Target not found in the list")

Best practices

  • Always ensure the loop condition will eventually become False, or include a break - otherwise you create an infinite loop
  • Use 'while True' with an explicit break when the exit condition is checked in the middle of the loop body, not just at the top
  • Prefer a for loop over a while loop whenever you are iterating a known number of times or over a sequence
  • The while...else construct is rarely used but is handy for 'search and report if not found' patterns

At a glance

Purpose
Scripting and general-purpose applications
File extension
.py
Runs in
Python interpreter
Usually used with
Python standard library and packages

Specifications & further reading

Related Python documentation