Python while Loop
A while loop repeats a block of code as long as a condition remains True. Be careful to update the condition inside the loop to avoid infinite loops.
Basic while Loop
Prints numbers from 1 to 5.
i = 1
while i <= 5:
print(i)
i += 1
Try it Yourself →
while-else
The else block runs once when the condition becomes False. It does not run if the loop is stopped by break.
num = 1
while num <= 3:
print(num)
num += 1
else:
print("Loop finished naturally")
Try it Yourself →
Countdown with while
A classic countdown example showing decrement and a stopping condition.
count = 5
while count > 0:
print(f"T-minus {count}")
count -= 1
print("Liftoff!")
Try it Yourself →