while loop in Python

This tutorial will teach you how to utilise the Python while statement to run a code block as long as a condition is true.

While in Python, if a condition is True, you can run a code block repeatedly.

The Python while statement is shown in the following syntax:

while condition:  
   body

The condition is a boolean expression that returns True or False when evaluated.

At the start of each iteration, the while statement examines the condition. As long as the condition is True, it will execute the body.

You must do something to stop the loop at some point in the loop’s body.

Otherwise, you’ll have an endless loop that won’t stop until you close the programme.

It’s termed a pretest loop because the while statement verifies the condition at the start of each iteration.

The while statement will do nothing if the condition is False from the start.

Example of a simple while statement in Python

The while statement is used in the following example to display 5 integers from 0 to 4 on the screen:

max = 5
counter = 0

while counter < max:
    print(counter)
    counter += 1

Output

0 1 2 3 4

How does it work?

To begin, set the starting values of max and counter to five and zero, respectively.
Second, employ the while statement in conjunction with the condition counter max. It’ll run the loop body as long as the counter value is less than max.
Third, display the counter variable’s value and increment it by one with each repetition. When the counter reaches 5, the condition counter max evaluates to False, and the loop ends.