The While Loop
What is a While Loop?
A while loop executes a set of statements as longs as the test expression is true. A statement is executed only once from top to bottom. The while loop is useful to execute a group of statements several times repeatedly depending on whether a condition is True of False.
Syntax of While Loop:
while conditions: statements
Python interpreter first checks the condition. If the condition is true, then it execute the statements written below colon(:). After executing statements, it go back and check the condition again. If the condition is again found to true. Then it continue and so on until condition is true. Once the condition is found to be false, then it come out of the while loop.
Example for While Loop:
A python program to display number from 1 to 10 using while loop
#A python program to display number from 1 to 10 using while loop x=1 while x<=10: print(x) x+=1 print("End") #Output: 1 2 3 4 5 6 7 8 9 10 End
A python program to display even numbers between 100 and 200.
#A python program to display even numbers between 100 and 200. x=100 while x>=100 and x<=200: print(x) x+=2 print("End") #Output: 100 102 104 ... ... ... 196 198 200 End