Open-Source Python Lesson #5: While Loops, Break, and Continue

Python #5 builds on Python #4 by introducing while loops and condition-controlled repetition. A while loop keeps running while its condition remains true, making it useful when the number of repetitions is not known in advance.

Bitcoin Mining Example: Cooldown Monitor

temperature_c = 92

while temperature_c > 80:
    print("Cooling ASIC:", temperature_c, "C")
    temperature_c -= 3

print("Temperature back in range")

The loop continues until the simulated ASIC temperature falls to 80°C or below. Real monitoring software would read telemetry rather than subtracting a fixed value, but the control-flow principle is the same.

Gaming Example: Keep Playing Until Health Reaches Zero

health = 30

while health > 0:
    print("Player health:", health)
    health -= 10

print("Game over")

Use break

attempt = 1

while True:
    print("Checking miner connection:", attempt)

    if attempt == 3:
        print("Miner connected")
        break

    attempt += 1

while True would otherwise run indefinitely. break immediately exits the nearest loop when the connection condition is met.

Use continue

player_number = 0

while player_number < 5:
    player_number += 1

    if player_number == 3:
        continue

    print("Process player", player_number)

continue skips the rest of the current iteration. Here player 3 is skipped, while the loop continues with players 4 and 5.

Sports Example: Overtime

home_score = 24
away_score = 24
overtime = 1

while home_score == away_score:
    print("Overtime period:", overtime)

    home_score += 3
    overtime += 1

print("Final:", home_score, "-", away_score)

This simplified example repeats while the score remains tied. Condition-driven repetition is useful for simulations where the stopping point depends on events rather than a predetermined count.

Avoid Accidental Infinite Loops

Always identify what can eventually make a while condition false, or provide an intentional exit such as break. Otherwise the loop can continue indefinitely.

Video Lesson

Real Python’s lesson focuses specifically on using break and continue with Python while loops and demonstrates the control flow through practical examples.

Practice

  1. Write an ASIC-temperature loop that stops when temperature reaches a safe threshold.
  2. Create a game-health loop that ends at zero.
  3. Use break to exit a simulated connection retry loop.
  4. Use continue to skip one player number.
  5. Explain when you would choose while instead of for.

Key Takeaway

Use for when iterating through an iterable or known sequence. Use while when repetition should continue according to a condition. break exits a loop and continue advances to its next iteration.

Leave a comment