The while loop in Python is one of the most general ways to perform iteration. While loop is a control loop statement that allows code to be executed repeatedly based on a given condition.
Syntax for a While Loop in Python
1 2 3 4 | while <condition>: statement else: statement |
The else part is not necessary to end while loop, but when used then it gets executed when while loop terminates.
Python Example using While Loop
1 2 3 4 5 | # print 0 to 9 using while loop x=0 while x<10: print("result:",x) x=x+1 |
Output
1 2 3 4 5 6 7 8 9 10 | result: 0 result: 1 result: 2 result: 3 result: 4 result: 5 result: 6 result: 7 result: 8 result: 9 |
While loop using else:
1 2 3 4 5 6 7 | #using while and else x=0 while x<10: print("result",x) x+=1 else: print("thanks") |
Output
1 2 3 4 5 6 7 8 9 10 11 | result: 0 result: 1 result: 2 result: 3 result: 4 result: 5 result: 6 result: 7 result: 8 result: 9 thanks |
Note: If the while loop condition never results false, then the loop will run endless times i.e infinity.
Comment for any suggestion or doubts.