Python - While Loops

Overview

Estimated time: 15–25 minutes

Use while loops for condition-driven repetition, with safe termination patterns.

Learning Objectives

  • Write while loops with clear termination conditions.
  • Use break, continue, and else with loops.
  • Prefer for when iterating over collections.

Prerequisites

Examples

n = 3
while n > 0:
    print(n)
    n -= 1
else:
    print("done")

Breaking and continuing

i = 0
while True:
    i += 1
    if i % 2 == 0:
        continue
    if i > 5:
        break
    print(i)

Common Pitfalls

  • Forgetting to update the loop variable → infinite loop.
  • Using while True without a clear and reachable break.

Checks for Understanding

  1. When does the else on a loop execute?
  2. How do you avoid infinite loops?
Show answers
  1. When the loop finishes without hitting break.
  2. Ensure the condition changes and/or include a clear break path.

Exercises

  1. Read integers from input until 0 is entered; print their sum.
  2. Implement a guessing game with at most 5 attempts.