I1 · Python Programming for AI

while Loops, break and continue

A while loop repeats a block of code as long as its condition stays True, checking the condition before each repeat. break exits the loop immediately, and continue skips the rest of the current repeat and goes back to the condition. A loop whose condition never becomes False runs forever.

10 min Intermediate · Sublevel Beginner Jump to the activity

What you need: The earlier topics of this module.

Definition

How does a game keep going until you win?

A while loop repeats a block of code as long as its condition stays True, checking the condition before each repeat. break exits the loop immediately, and continue skips the rest of the current repeat and goes back to the condition. A loop whose condition never becomes False runs forever.

In simple words

Use for when you know how many times to repeat. Use while when you repeat until something happens: until the guess is right, until the tank is full, until the user types 'quit'. Always make sure something inside the loop moves it towards stopping.

Overview

  • A while loop repeats its block as long as a condition stays True.
  • The condition is checked before every pass, so the loop may run zero times.
  • Something inside the loop must eventually make the condition False, or it runs forever.
  • break exits a loop at once; continue skips the rest of the current pass.
  • pass does nothing and is used as a placeholder where a statement is required.
  • Use for when you know how many times to repeat; use while when you repeat until something happens.

Why it matters

Chatbots wait for messages until the user leaves, games run until someone wins, and training continues until the error is small enough. All of these are while loops.

Key terms

while loop
Repeats a block as long as its condition is True.
Loop condition
The expression checked before each repeat of a while loop.
break
Leaves the loop immediately.
continue
Skips the rest of this repeat and starts the next one.
Infinite loop
A loop whose condition never becomes False.
Sentinel value
A special input, such as "quit", that signals the loop to stop.

Types

while loops are grouped by what controls when they stop. There are also three loop-control statements. These are the main types.

1. Counter-controlled loop

A loop that runs a known number of times using a counter variable.

  • How it works: Set the counter, test it in the condition, and change it inside the loop: i = 1; while i <= 5: ...; i += 1.
  • Example: Printing the numbers 1 to 5 with a while loop.
  • When to use it: Use it to learn loops; in practice, a for loop with range() is usually clearer for counting.

2. Sentinel-controlled loop

A loop that keeps reading values until a special stop value, the sentinel, appears.

  • How it works: The program reads a value, stops if it equals the sentinel, otherwise processes it and reads the next.
  • Example: Adding marks until the user types -1: while mark != -1: total += mark; mark = int(input()).
  • When to use it: Use it when the amount of input is unknown in advance.

3. Validation loop

A loop that keeps asking until the input is acceptable.

  • How it works: It checks the input against rules and repeats the question with a helpful message whenever a rule is broken.
  • Example: while not (1 <= age <= 120): age = int(input("Enter a valid age: "))
  • When to use it: Use it for every user input that must be within a range or format.

4. Infinite loop with break

A loop written as while True that exits only through a break statement.

  • How it works: The loop body checks the exit condition somewhere in the middle and calls break when it is met.
  • Example: A menu that repeats until the user chooses "q" to quit.
  • When to use it: Use it for menus, games and servers that run until told to stop.

5. Loop-control statements: break, continue, pass and else

Statements that change the normal flow inside for and while loops.

  • How it works: break ends the loop; continue jumps to the next pass; pass does nothing; a loop's else block runs only if the loop ended without break.
  • Example: Searching a list: break when the name is found; the else block prints "Not found".
  • When to use it: Use break to stop early, continue to skip bad items, and else to handle the "nothing found" case cleanly.

Explained in detail

for or while?

Use for when you know what you are looping over: every item in a list, every number in a range. Use while when you do not know in advance how many repeats you need, only the condition for stopping: keep asking until the input is valid, keep halving until the number is below 1, keep the game running until the player quits. Every while loop must do something inside its body that can eventually make the condition False. If nothing changes, the loop runs forever.

Common while patterns

PatternShapeExample use
Input validationAsk, check, ask again while invalidA mark between 0 and 100
Sentinelwhile True: read; if it is "quit", breakA chatbot conversation
ConvergenceRepeat until the change is tinyGradient descent steps
Counting with a conditionCount steps until a target is reachedYears until savings double

break, continue and else

break ends a loop at once and jumps to the first line after it. It is ideal for searching: stop as soon as you find what you want. continue skips to the next repeat, which is useful for ignoring items that do not interest you, such as blank lines in a file. Python also allows an else block after a loop. It runs only if the loop finished normally, without a break. That makes search code neat: for item in items: if found: break, followed by else: print("not found").

Avoiding infinite loops

  1. Identify the variable the condition depends on.
  2. Make sure the loop body changes it, every time, in the right direction.
  3. Prefer conditions such as < or >= over == for numbers, so a skipped value cannot trap the loop.
  4. For loops that wait for something outside your control, add a maximum number of attempts.
  5. If a program hangs, press Ctrl+C in a terminal, or the stop button in a notebook, to interrupt it.

Some infinite loops are deliberate. Servers, games and operating systems run while True: loops that wait for events and only stop when told to. The difference is that they have a clear exit, a break or a shutdown signal, built in.

How it works

attempts = 0
while attempts < 3:
    attempts += 1          # without this line the loop never ends
    print("Attempt", attempts)
  • break: stop the loop now, for example when the answer is found.
  • continue: skip this repeat, for example to ignore a blank entry.
  • while True: with a break inside is a common pattern for menus and chats.

In code

A number-guessing game. The guesses are listed in advance so it runs the same everywhere; on your computer you could use input().

guessing_game.py
secret = 7
guesses = [3, 9, 0, 7, 5]

tries = 0
while tries < len(guesses):
    guess = guesses[tries]
    tries += 1
    if guess == 0:
        print("0 isn't allowed, skipping")
        continue
    if guess == secret:
        print("Guess", guess, "is right! Tries:", tries)
        break
    print("Guess", guess, "is", "too low" if guess < secret else "too high")

countdown = 3
while countdown > 0:
    print(countdown)
    countdown -= 1
print("Lift off!")

Output

Guess 3 is too low
Guess 9 is too high
0 isn't allowed, skipping
Guess 7 is right! Tries: 4
3
2
1
Lift off!

Try it yourself

Predict the output

What does each loop print?

  • n starts at 1. While n < 4: print n, then add 1 to n.
  • For n in range(5): if n is 3, break; otherwise print n.
  • For n in range(5): if n is 2, continue; otherwise print n.
  • n starts at 10. While n > 10: print n.

Common mistakes

  • Forgetting to change the variable in the condition: an infinite loop.
  • Using while when a for loop over a list would be simpler.
  • Putting break outside a loop.

Check yourself

Question 1

1. What does break do?

Question 2

2. When is while better than for?

Question 3

3. What causes an infinite loop?

Summary

  • while repeats as long as its condition is True.
  • break exits; continue skips to the next check.
  • Always change something that moves the loop towards stopping.

Finished reading?

Sources: W3Schools: Python While Loops