Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

while-loop
loops
python

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

Educative Answers Team

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

RELATED TAGS

while-loop
loops
python
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring