Python Foundations · Lesson 7 of 12

Condition-controlled loops

while loops, sentinels and avoiding infinite loops. Learn through short examples, practical tasks and targeted questions.

← All lessons

Repeating with while

A while loop checks its condition before every repetition. It works well for menus and input that continues until a sentinel value is entered. Identify which variable changes inside the loop and explain how the program eventually stops.

Watch out: If the loop condition never becomes false, the program can repeat indefinitely. Check both the starting state and the update.

1 · Understand

while loops, sentinels and avoiding infinite loops. Study the code and predict what it does before running it. Change a value or string and observe how the output changes.

counter = 3
while counter > 0:
    print(counter)
    counter -= 1
print("Go!")
Download example .py ↓

2 · Practise

Build a simple menu that repeats until the user enters Q.

Plan your inputs, processing and outputs. Write the code in Mu, IDLE or PyCharm; test at least three cases.

Show a reference solution after attempting the task
choice = ""
while choice != "Q":
    choice = input("A to continue; Q to quit: ").upper()
print("Goodbye")
Download reference solution .py ↓

3 · Debug the code

Identify the problem and explain how to fix it before revealing the answer.

count = 0
while count < 3:
    print(count)
Reveal the corrected program and explanation
count = 0
while count < 3:
    print(count)
    count += 1

Compare the two snippets. Identify the changed line, run the corrected version and explain the effect.

4 · Check your understanding

What is the main risk when a while condition never becomes false?

5 · Challenge and reflect

Extension: Improve your solution to deal with unexpected input, add a second feature or display results more clearly.

Reflect: What was the hardest part? What would you test if someone else used your program?

Want extra practice? Try interactive Python tracing and debugging questions →

APPLY THE IDEA

Use this skill beyond the example

A while loop only terminates if the condition eventually becomes False or the loop exits another way. Check that the loop variable changes and practise a dry run with the smallest valid input.

Quick check: Why might while total < 10 become an infinite loop?

Check: If total never changes enough to make the condition False, the loop cannot terminate normally.