← Back to Chapters

Python While Loops

? Python While Loops

✨ Quick Overview

In Python, a while loop repeatedly executes a block of code as long as a given condition is True. It is useful when you do not know in advance how many times you want to repeat a block, and the repetition depends on a condition (like user input or a counter reaching a limit).

? Key Concepts

  • Condition-based loop: The loop continues running while the condition is True.
  • Loop variable: A variable (like a counter) often controls when the loop should stop.
  • Infinite loop: Happens if the condition never becomes False.
  • break statement: Used to exit a loop early.
  • Python and do-while: Python has no built-in do-while, but you can emulate it with while True and break.

? Syntax and Theory

The basic syntax of a while loop is:

? View While Loop Syntax
while condition:
    # code block
    # runs as long as condition is True

Before each iteration, Python evaluates condition. If it is True, the body of the loop runs; if it is False, the loop stops and control moves to the next statement after the loop.

? Code Examples

? Basic While Loop

This example uses a counter variable that starts at 0 and increments until it reaches 5.

? View Code Example
count = 0
# Initialize the counter
while count < 5:
    # Loop while count is less than 5
    print("Count:", count)
    # Increase count to avoid an infinite loop
    count += 1

♾️ Infinite Loop with Break

A while True loop runs forever unless you manually exit using break. This pattern is common when waiting for user input.

? View Code Example
# Loop indefinitely until the user types 'exit'
while True:
    user_input = input("Type 'exit' to stop: ")
    # Check if the user wants to stop the loop
    if user_input == "exit":
        # Exit the loop using break
        break

? Emulating a Do-While Loop

Many languages have a do-while loop that runs the body at least once before checking the condition. Python does not have this construct, but you can emulate it:

? View Code Example
# Run the block at least once and then check the condition
while True:
    print("This runs at least once")
    if not condition:  # replace 'condition' with your check
        # Break when the condition is no longer satisfied
        break

Here, the code inside the loop always executes once. The if not condition check decides when to exit using break, giving you do-while-like behaviour.

? Live Output / Explanation

For the basic while loop example:

The program prints:

Count: 0
Count: 1
Count: 2
Count: 3
Count: 4

After printing Count: 4, the variable count becomes 5. The condition count < 5 is now False, so the loop stops.

In the infinite loop example, the program keeps asking for input until you type exit. At that point, the if condition becomes True, break is executed, and the loop ends.

✅ Tips and Best Practices

  • Always ensure your while loop has a condition that will eventually become False to avoid infinite loops.
  • Update loop variables inside the loop (e.g., count += 1) so that the condition can change.
  • Use break to exit loops early when a certain condition is met (e.g., correct input received).
  • When emulating a do-while loop, use while True with a carefully designed break condition.
  • Be cautious with user input in loops; handle invalid input gracefully to avoid unexpected behaviour.

? Try It Yourself

  • Write a while loop to print numbers from 10 down to 1.
  • Create a loop that keeps asking for a password until the user enters the correct one, then prints a success message.
  • Simulate a do-while loop using while True that asks the user to enter a number and stops only when they enter a positive number.
  • Modify the basic counter example so that it prints only even numbers between 0 and 20.