Control Flow

While Loops

A

while
loop continues as long as a condition is true.

Basic While Loop

count = 0

while count < 5:
    print(count)
    count += 1

Be Careful!

A while loop can run forever if the condition never becomes false:

# DANGER: Infinite loop!
while True:
    print("This never stops!")

Break and Continue

  • break
    : Exit the loop immediately
  • continue
    : Skip to the next iteration
while True:
    answer = input("Type 'quit' to exit: ")
    if answer == "quit":
        break
    print(f"You typed: {answer}")
Visualizer
while loop iteration
5
4
3
2
1
✓ Loop completed

Interactive Visualization

python
Loading...
Output
Run execution to see output...