While Loops
Looping with While
A
while loop repeats code as long as a condition is True. Unlike for loops, you control when to stop by changing the condition.python
count = 0
while count < 5:
print(f"Count is {count}")
count += 1
print("Done!")Break and Continue
Use
break to exit a loop early, and continue to skip to the next iteration.python
# break example
for i in range(10):
if i == 5:
break
print(i) # Prints 0-4
# continue example
for i in range(5):
if i == 2:
continue
print(i) # Prints 0, 1, 3, 4Tip:Be careful with while loops! If the condition never becomes False, you'll create an infinite loop. Always make sure something changes inside the loop.
PlaygroundPython
Output
Click "Run" to see output