🌱BeginnerControl Flow

while Loops

Repeating code as long as a condition holds with while loops.

Overview

A while loop executes a block of code repeatedly as long as a condition remains truthy. Unlike a for loop which iterates a fixed number of times over a sequence, a while loop is appropriate when you don't know in advance how many iterations you need for example, waiting for user input, processing data until a sentinel value, or converging on a result. The most important thing to ensure with a while loop is that the condition will eventually become False otherwise you create an infinite loop that runs forever (or until you kill the program with Ctrl+C). The break and continue statements work in while loops exactly as they do in for loops. A common pattern is the "loop-and-a-half": while True: ... break, which is useful when the exit condition naturally appears in the middle of the loop body.

Key Points

  • •while condition: runs the body as long as condition is truthy
  • •Always ensure something inside the loop will eventually make the condition False
  • •break exits the loop immediately; continue skips to the re-check of the condition
  • •while True: with a break inside is a valid pattern for "loop until a condition mid-body"
  • •while loops also support an else clause runs when the condition becomes False (not via break)
  • •Be careful with floating-point conditions use an epsilon for termination, not exact equality

Examples

Basic while loop with a counter

count = 1
while count <= 5:
    print(count)
    count += 1     # must update count or loop runs forever
# prints 1 2 3 4 5

while True with break loop-and-a-half pattern

# Simulate a password prompt
password = "secret"
attempts = 0
while True:
    guess = input("Enter password: ")
    attempts += 1
    if guess == password:
        print(f"Access granted after {attempts} attempt(s).")
        break
    print("Wrong password, try again.")

while True: ... break is clean when the exit condition belongs in the middle of the body.

Finding the first power of 2 greater than 1000

n = 1
while n <= 1000:
    n *= 2
print(n)   # 1024

Common Mistakes

  • Infinite loop: forgetting to update the variable the condition depends on
  • Off-by-one: using < vs <= incorrectly at the boundary value
  • Testing float equality in while condition: `while x != 0.0` can loop forever due to floating-point imprecision use `while abs(x) > 1e-9` instead

Note

If you are rewriting a for loop as a while loop, ask yourself why. For loops over known sequences are almost always clearer. Use while when the exit condition is dynamic or unknown upfront.

Exercises

Write Python code to solve each exercise. Run it in your browser and check your output.

Loading editor…

Completed: 0 / 5 exercises

Knowledge Check

Question 1 of 4

When does a while loop stop executing?