Nishaglobal Education logo

while loops, break and continue

Repeat code while a condition stays true with Python's while loop, stop early with break, skip with continue, avoid infinite loops and build a guessing game and a menu.

Lesson 9 of 1425 minQuiz: 4 questions

🎯 By the end of this lesson you will be able to:

  • Write a while loop that stops when a condition becomes false
  • Use break to leave a loop and continue to skip to the next round
  • Choose between for and while, and stop an infinite loop
Outline
  1. What you'll learn and why it matters
  2. Repeating while a condition is true
  3. break: leaving a loop early
  4. continue: skipping to the next round
  5. Worked example: a simple menu
  6. Practice
  7. Common mistakes
  8. Recap
  9. Quiz
  10. Mark lesson complete

What you'll learn and why it matters

A for loop is perfect when you know what to loop over. But sometimes you do not know how many times to repeat: keep asking until the user types a valid answer, keep a menu open until they choose Quit, keep saving until you reach a goal. That is the job of the while loop.

Repeating while a condition is true

while checks a condition. If it is true, it runs the indented block, then goes back and checks again. It stops as soon as the condition is false.

Python
savings = 0
week = 0
while savings < 1000:
    week += 1
    savings += 300
    print(f"Week {week}: saved {savings}")
print(f"Goal reached in {week} weeks!")

Output

Week 1: saved 300
Week 2: saved 600
Week 3: saved 900
Week 4: saved 1200
Goal reached in 4 weeks!
savings < 1000 ?checked before every roundTrueRun the indented blockweek += 1, savings += 300repeatFalseCarry on after the loopSomething in the block must move the check towards False
A while loop checks its condition before every round. While it is true, the block runs and Python jumps back to check again; once it is false, the program continues after the loop.
Checksavings < 1000?What happens
10 < 1000 → Trueweek 1, savings 300
2300 < 1000 → Trueweek 2, savings 600
3600 < 1000 → Trueweek 3, savings 900
4900 < 1000 → Trueweek 4, savings 1200
51200 < 1000 → Falseloop ends

break: leaving a loop early

break stops the loop immediately, even if the condition is still true. A common pattern is while True: (repeat forever) with a break when you are done. This is how you write a program that keeps asking until it gets an answer:

Python
secret = 7
guesses = 0
while True:
    guess = int(input("Guess the number (1-10): "))
    guesses += 1
    if guess == secret:
        print(f"Correct! You took {guesses} guesses.")
        break
    elif guess < secret:
        print("Too low, try again.")
    else:
        print("Too high, try again.")

Output (you type: 4, 9, 7)

Guess the number (1-10): 4
Too low, try again.
Guess the number (1-10): 9
Too high, try again.
Guess the number (1-10): 7
Correct! You took 3 guesses.

The example output shows a player typing 4, then 9, then 7. In lesson 14 you will use the random module so the secret number changes every game.

continue: skipping to the next round

continue jumps straight back to the top of the loop, skipping the rest of the block for this round. It works in for loops too:

Python
readings = [32, -999, 35, 31, -999, 34]
total = 0
count = 0
for reading in readings:
    if reading == -999:
        continue
    total += reading
    count += 1
print(f"Average of {count} good readings: {total / count}")

Output

Average of 4 good readings: 33.0

Here -999 means the sensor failed. continue skips those values so they do not spoil the average.

Most interactive programs, including your final project, are built around a menu loop like this:

Python
balance = 500
while True:
    print("1) Check balance  2) Add money  3) Quit")
    choice = input("Choose: ")
    if choice == "1":
        print(f"Balance: {balance}")
    elif choice == "2":
        amount = int(input("Amount to add: "))
        balance += amount
        print("Added.")
    elif choice == "3":
        print("Goodbye!")
        break
    else:
        print("Please type 1, 2 or 3.")

Output (you type: 2, 250, 1, 3)

1) Check balance  2) Add money  3) Quit
Choose: 2
Amount to add: 250
Added.
1) Check balance  2) Add money  3) Quit
Choose: 1
Balance: 750
1) Check balance  2) Add money  3) Quit
Choose: 3
Goodbye!

Practice

Guided exercise

Countdown

Ask for a starting number and count down to 1 with a while loop, then print Lift off!.

  1. Read the number into n with int(input(...)).
  2. Loop while n > 0:, print n, then subtract 1 with n -= 1.
  3. After the loop, print Lift off!.
Show the solution
Solution
n = int(input("Start from: "))
while n > 0:
    print(n)
    n -= 1
print("Lift off!")

Output (you type: 3)

Start from: 3
3
2
1
Lift off!

How to get there: n -= 1 makes the condition move towards false; without it, the loop would never end.

Your turn

Keep asking for a valid age

Keep asking Age: until the user enters a number between 1 and 120, then print Thank you. Use while True and break.

Show the solution
Solution
while True:
    age = int(input("Age: "))
    if 1 <= age <= 120:
        break
    print("Please enter an age between 1 and 120.")
print("Thank you")

Output (you type: 0, 150, 34)

Age: 0
Please enter an age between 1 and 120.
Age: 150
Please enter an age between 1 and 120.
Age: 34
Thank you

How to get there: Python lets you chain comparisons: 1 <= age <= 120 means age is at least 1 and at most 120. The example shows a user typing 0, then 150, then 34.

Common mistakes

Forgetting to change the variable in the condition

You see: The program never stops (infinite loop)

Fix: Make sure something inside the loop moves the condition towards false. Press Ctrl + C to stop it.

while True with no break

You see: The program never stops

Fix: Add a break for the exit case (such as the Quit option).

Comparing the menu choice to a number

You see: Choosing 1 does nothing: "1" == 1 is False

Fix: input() returns a string, so compare with "1", or convert with int().

Putting break outside the loop

You see: SyntaxError: 'break' outside loop

Fix: break and continue only work inside a loop's indented block.

Recap

  • while condition: repeats while the condition is true, checking before every round.
  • Something inside the loop must eventually make the condition false, or use break.
  • break leaves the loop immediately; continue skips to the next round.
  • while True plus break is the standard pattern for menus and repeated questions.

Key terms

while loop
A loop that repeats while a condition is True.
Infinite loop
A loop whose condition never becomes False, so it never ends.
break / continue
break leaves a loop; continue skips to its next round.

Check your understanding

Answer all 4 questions, then check your answers to see an explanation for each one.

  1. 1. What does this print? n = 1 while n < 20: n = n * 3 print(n)

  2. 2. A program with `while True:` never ends. What is missing?

  3. 3. What does `continue` do?

  4. 4. Which job suits a while loop better than a for loop?

Answer all 4 questions to check.

Mark this lesson complete

Finished this lesson?

When you have worked through the examples and exercises, mark it complete to save your progress.