How do you execute a 'while loop' in Python?

What is a ‘while loop’?

A while loop consists of a condition and until that condition is true, a set of statements is executed repeatedly.

A while loop is the only necessary repetition construct. The for loop, can be duplicated using a while loop, and with more control.

The syntax is as follows:

Example

Here’s a look at the while loop code:

x=4
y=0
while (y <= 10 ): ## the while loop will run till y<=10 condition is being met
y += x
x += 1
## the loop will iterate 3 times
print "the value of x is:",x
print "the value of y is:", y

Explanation

In the code above, the while loop runs as long as the condition, y<=10, is being met. The statements on line 4 and line 5 execute if the expression inside the parenthesis evaluates to true.

When the expression evaluates to false the program comes out of the loop and prints the final values of x and y.

Below is an illustration of the code above to help illustrate the logic.

Flow Chart For While Loop Code

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved