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

Latest Current Affairs 2024 Online Exam Quiz for One day Exam Online Typing Test CCC Online Test 2024 Python Programming Tutorials Best Computer Training Institute in Prayagraj (Allahabad) Best Java Training Institute in Prayagraj (Allahabad) Best Python Training Institute in Prayagraj (Allahabad) O Level Online Test in Hindi Bank SSC Railway TET UPTET Question Bank career counselling in allahabad Sarkari Naukari Notification Best Website and Software Company in Allahabad Sarkari Exam Quiz