The while Loop for Beginners

The while loop lets you run a block of code as long as its condition is true. Indentation works just like with the if statement—everything indented by four spaces relative to the while keyword is part of the loop’s body.

In English, “while” means “as long as.”

Understanding how the loop works is crucial for beginners. Let’s look at a program that outputs numbers from 1 to 3, one per line:

i = 1
while i <= 3:
    print(i)
    i += 1
  • Set an initial value for i, known as a counter variable.
  • Declare the condition—as long as the counter is less than or equal to three, the code below runs. End the condition with a colon.
  • Output the value of i (one, in this case). Python identifies the loop’s start by the four-space indentation.
  • Increase i by one (making it two). Is two less than or equal to three? If yes, Python performs another loop iteration. This continues until the condition is false (when i is greater than three).

We can rewrite our program using the break statement:

i = 1
while True:
    print(i)
    if i >= 3:
        break
    i += 1

The loop’s repetitions and steps are similar to the first version. The difference is that we use the break statement to end the loop. If the counter variable is greater than or equal to 3, the loop stops. The break statement is helpful if writing the condition in while is difficult, cumbersome, or if you need to perform additional actions before ending the loop.