Python while loop iterates the block of code repeatedly till it satisfies the specified condition. It is used when the number of iterations is not known before.
while expression: # statements
i = 1 while i < 5 print(i) i++
1 2 3 4
Infinite while loop
Any non-zero value in the while loop indicates an always true condition whereas 0 indicates an always false condition.
while(2) print(“This is infinite while loop”)
This is infinite while loop This is infinite while loop (infinite times)
else statement with while loop
Python allows us to use the else statement with the while loop which is executed only when the condition given in the while statement becomes false, But if the while loop contains any break statement then the else statement will not be executed.
i = 1 while i < 5 print(i) i++ else:print(“while loop is exhausted”)
1 2 3 4
i = 1 while i < 5 print(i) i++ if(i==3) break; else:print(“while loop is exhausted”)
1 2 Loop is broken due to break statement