Python while

Summary: in this tutorial, you’ll learn about the Python while statement and how to use it to run a code block as long as a condition is true.

Introduction to the Python while statement #

Python while statement allows you to execute a code block repeatedly as long as a condition is True.

The following shows the syntax of the Python while statement:

while condition:  
   bodyCode language: Python (python)

The condition is an expression that evaluates to a boolean value, either True or False.

The while statement checks the condition at the beginning of each iteration. It’ll execute the body as long as the condition is True.

In the body of the loop, you need to do something to stop the loop at some time.

Otherwise, you’ll get an indefinite loop that will run forever until you close the application.

Because the while statement checks the condition at the beginning of each iteration, it’s called a pretest loop.

If the condition is False from the beginning, the while statement will do nothing.

The following flowchart illustrates the while loop statement: