What is a While Loop?
The while
loop in Python runs a block of code as long as a specified condition remains true.
Basic Syntax
while condition: # Code block to execute
Example: Simple While Loop
x = 0 while x < 5: print(x) x += 1
Using a Break Statement
The break
statement exits the loop when a condition is met.
x = 0 while x < 10: if x == 5: break print(x) x += 1
Using a Continue Statement
The continue
statement skips the rest of the current iteration and proceeds to the next.
x = 0 while x < 5: x += 1 if x == 3: continue print(x)
Else in While Loop
The else
block runs when the loop condition becomes false.
x = 0 while x < 3: print(x) x += 1 else: print("Loop completed")
Infinite Loop
Be careful when writing while loops without a proper condition, as they can run indefinitely.
while True: print("This will run forever!")