Python while loop

In Python, while loop is used to execute number of statements or body till the specified condition is true. Once the condition is false, the control will come out of the loop.

while loops are constructed like so :


while [a condition is True]:
    [do something]

Here, loop Body will execute till the expression passed is true. The Body may be a single statement or multiple statement.

Python While Loop Example :


a=10

while a>0:
    print "Value of a is",a
    a=a-2
print "Loop is Completed"

output of above example  :



Value of a is 10
Value of a is 8
Value of a is 6
Value of a is 4
Value of a is 2
Loop is Completed

Explanation:

1

Firstly, the value in the variable is initialized.

2

Secondly, the condition/expression in the while is evaluated. Consequently if condition is true, the control enters in the body and executes all the statements . If the condition/expression passed results in false then the control exists the body and straight away control goes to next instruction after body of while.

3

Thirdly, in case condition was true having completed all the statements, the variable is incremented or decremented. Having changed the value of variable step second is followed. This process continues till the expression/condition becomes false.

4

Finally Rest of code after body is executed.

Python While Loop Example 2 :





n=153
sum=0

while n>0:
    r=n%10
    sum+=r
    n=n/10
print sum

output of above example  :



9

An infinite loop occurs when a program keeps executing within one loop, never leaving it. To exit out of infinite loops on the command line, press CTRL + C.

This tutorial went over how while loops work in Python and how to construct them. While loops continue to loop through a block of code provided that the condition set in the while statement is True


advertisement