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
while: 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
# print 0 to 9 using while loop x=0 while x<10: print("result:",x) x=x+1
Output
result: 0 result: 1 result: 2 result: 3 result: 4 result: 5 result: 6 result: 7 result: 8 result: 9
While loop using else:
#using while and else x=0 while x<10: print("result",x) x+=1 else: print("thanks")
Output
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.