while loop is used when you want to perform a task indefinitely, until a particular condition is met.
It’s a condition-controlled loop.
Here’s the syntax of the
Any non-zero value or nonempty container is considered TRUE; whereas Zero, None, and empty container is considered FALSE.
Example: Iterate until x becomes 0
x = 6 while x: print(x) x -= 1 # 6 5 4 3 2 1
Example: Iterate until list is empty
L = ['red', 'green', 'blue'] while L: print(L.pop()) # blue green red
Example: Iterate until string is empty
x = 'blue' while x: print(x) x = x[1:] # blue # lue # ue # e
If the condition is false at the start, the
while loop will never be executed at all.
Example: Exit condition is false at the start
x = 0 while x: print(x) x -= 1
Break in while Loop
Python break statement is used to exit the loop immediately.
It simply jumps out of the loop altogether, and the program continues after the loop.
Example: Exit when x becomes 3
x = 6 while x: print(x) x -= 1 if x == 3: break # 6 5 4
Continue in while Loop
The continue statement skips the current iteration of a loop and continues with the next iteration.
Example: Skip odd numbers
x = 6 while x: x -= 1 if x % 2 != 0: continue print(x) # 4 2 0
Else in While Loop
Python allows an optional
else clause at the end of a
else clause will be executed when the loop terminates normally (the condition becomes false).
Example: else clause when loop terminates normally
x = 6 while x: print(x) x -= 1 else: print('Done!') # 6 5 4 3 2 1 # Done!
else clause will still be executed if the condition is false at the start.
Example: else clause when the condition is false at the start
x = 0 while x: print(x) x -= 1 else: print('Done!') # Done!
If the loop terminates prematurely with
else clause won’t be executed.
Example: else clause when loop terminates prematurely
x = 6 while x: print(x) x -= 1 if x == 3: break else: print('Done!') # 6 5 4
Infinte Loop (while true)
The condition must eventually become false. Otherwise, the loop will execute forever, creating an infinite/endless loop.
Example: Infinte loop with while statement
while True: print('Press Ctrl+C to stop me!')
You can safely implement an infinite loop in your program using a
Example: Implement infinite loop safely
while True: name = input('Enter name:') if name == 'stop': break print('Hello', name)
Enter name:Bob Hello Bob Enter name:Sam Hello Sam Enter name:stop