How does Python while loop work?

PythonServer Side ProgrammingProgramming

while statement is very popular looping statement in many languages including Python. Is general usage is −

while expr==True:
    stmt1
    stmt2
    .....

The block of statements with increased indent after : symbol will be repeatedly executed as long as expr remains true. Obviously, certain provision must be there inside the block which will eventually make expr to be false, otherwise the loop will be an infinite one.

Easiest way to do this is to form a counted loop. For that a counting variable is to be initialized before looping body and it is incremented on every iteration till counting variable reached desired count.

x=0
if x<10:
     x=x+1
     print (x)
raja
Published on 19-Feb-2018 23:53:58
Advertisements