While Statement

While Loop Statement


The syntax of while loop in Python has the following syntax:

Syntax:

while <condition>:
statements block 1
[else:
statements block2]

In the while loop, the condition is any valid Boolean expression returning True or False. The else part of while is optional part of while. The statements block1 is kept executed till the condition is True. If the else part is written, it is executed when the condition is tested False. Recall while loop belongs to entry check loop type, that is it is not executed even once if the condition is tested False in the beginning.

Example : program to illustrate the use of while loop - to print all numbers from 10 to 15

i=10 # intializing part of the control variable
while (i<=15): # test condition
print (i,end='\t') # statements - block 1
i=i+1 # Updation of the control variable

Output:

10 11 12 13 14 15

Example : program to illustrate the use of while loop - with else part

i=10 # intializing part of the control variable
while (i<=15): # test condition
print (i,end='\t') # statements - block 1
i=i+1 # Updation of the control variable
else:
print ("\nValue of i when the loop exit ",i)

Output: 

10 11 12 13 14 15

Value of i when the loop exit 16