While Loops & Loop Control
Learn how to repeat actions endlessly as long as a condition is met, and how to safely break out of loops.
The While Loop
Imagine you want to keep asking a user for a password until they get it right. You don't know how many tries it will take. This is where a while loop shines: it repeats a block of code as long as a condition remains True.
battery = 100
while battery > 0:
print(f"Battery at {battery}%. Device is running.")
battery -= 20 # Drain battery
print("Device shut down.")Taking Control: Break and Continue
Sometimes you need to interrupt the normal flow of a loop from the inside.
- break: Instantly kills the loop and escapes it entirely, regardless of the condition.
- continue: Skips the rest of the current cycle and jumps immediately back to the top of the loop.
# Infinite loop setup
while True:
cmd = input("Type 'exit' to quit: ")
if cmd == 'exit':
print("Goodbye!")
break # Escapes the infinite loop safely
else:
print("You typed:", cmd)