Beginner   Chapter 64 · 30 min read · Module 5: Control Flow

while Loop

Learning objectives
  • After this chapter you can write a while loop with a correct condition and update step.
  • You can avoid and fix infinite loops.
  • You can use input validation loops and sentinel values.
  • You can use break, continue and else with while.
  • You can choose between while and for for a given task.

A while loop repeats a block of code as long as a condition stays true. Before every iteration Python checks the condition. If it is true, the body runs; if it is false, the loop ends. This is different from a for loop, which walks through a known collection.

The while loop is the right tool when you do not know in advance how many repeats are needed. Examples are asking for a password until it is correct, running a game until the player quits, or halving a number until it is small enough.

Because you control the condition yourself, you must also make sure it eventually becomes false. In this chapter you will learn the pattern, the common traps and the helpful extras like break, continue and else.

How a while loop works

The structure is simple: the keyword while, a condition and a colon, followed by an indented body. Python tests the condition first. If the condition is false the very first time, the body is skipped completely. After each run of the body Python goes back and tests the condition again.

Example 1: counting up
n = 1
while n <= 5:
    print(n)
    n += 1
print('Finished, n is', n)
1 2 3 4 5 Finished, n is 6

Notice that after the loop, n is 6. The loop stopped because n <= 5 became false. Knowing the value of the variable after the loop is useful in exams and in real code.

Loop condition: an expression checked before every iteration. The loop continues only while it is true.

The three parts: start, test, update

  1. Start: set the variable before the loop, for example n = 1.
  2. Test: write the condition in the while line, for example n <= 5.
  3. Update: change the variable inside the body, for example n += 1.

If the update is missing or goes the wrong way, the condition may never become false. Then the loop runs forever. This is called an infinite loop. In a terminal you can stop it with Ctrl+C.

Unknown number of repeats

The next example halves a number until it drops below 1. We do not know in advance how many steps it will take, which makes this a natural job for a while loop. Integer division with // keeps the numbers whole.

Example 2: halving
n = 100
steps = 0
while n > 1:
    n = n // 2
    steps += 1
print(steps, n)
6 1

Input validation and sentinel values

A very common use is asking for input again until it is acceptable. A sentinel value is a special input that tells the loop to stop, such as the word done. The example below reads lines from a prepared input so that it can run anywhere. Each line is a number to add, and done ends the loop.

Example 3: sentinel loop
total = 0
while True:
    text = input()
    if text == 'done':
        break
    total += int(text)
print('Total:', total)
Total: 22

The condition while True looks dangerous, but it is safe when the body contains a break that is reached under some situation. This pattern keeps the code short when the stopping test is in the middle of the body.

break, continue and else

break stops the loop immediately. continue skips the rest of the body and goes back to test the condition, so take care that the update happens before it or the loop may never end. A while loop can have an else block too. It runs when the condition becomes false normally, but not when break ends the loop.

Example 4: continue with care
n = 0
while n < 6:
    n += 1
    if n % 2 == 0:
        continue
    print(n)
1 3 5
Example 5: while else
attempts = 0
while attempts < 3:
    attempts += 1
    if attempts == 5:
        break
else:
    print('Loop ended normally after', attempts)
Loop ended normally after 3
In Example 4 the update n += 1 comes before continue. If you moved it after continue, the odd numbers would work but for even numbers the update would be skipped and the loop would get stuck.

while or for?

SituationBetter choice
Go through every item of a listfor
Repeat exactly 10 timesfor with range(10)
Repeat until the user types quitwhile
Repeat until a value is small enoughwhile

Any for loop can be rewritten as a while loop, but not always the other way in a simple manner. When both fit, a for loop is usually shorter and safer because the update is automatic.

Practical safety tips

  • Write the update line right after you write the while line, so you do not forget it.
  • Add a counter limit while testing, for example break after 1000 iterations.
  • Print the loop variable while debugging to see the changes.
  • Use comparisons like <= and < with care; they decide whether the last value is included.

Floating point numbers can also cause surprises. A loop like while x != 1.0 with x increased by 0.1 may never hit exactly 1.0 because of small rounding errors. Prefer < or <= for such tests.

Python syntax

Syntax
while condition:
    body
Syntax
while True:
    if stop_test:
        break
Syntax
while condition:
    body
else:
    runs_if_no_break

Real-world applications

  • Menus that repeat until the user chooses exit.
  • Validating user input.
  • Games that run until the player wins or loses.
  • Numerical methods that repeat until a result is accurate enough.
  • Reading data until an end marker appears.

Common mistakes

Mistake: Forgetting to update the loop variable.
Fix: Add the update such as n += 1 inside the body.
Mistake: Updating in the wrong direction, for example n -= 1 when counting up.
Fix: Trace the first few iterations on paper.
Mistake: Placing continue before the update step.
Fix: Do the update before continue.
Mistake: Using != with floating point numbers.
Fix: Use < or <= for float conditions.
Mistake: Off-by-one errors such as < versus <=.
Fix: Check the first and last values the loop should handle.

Important tips

  • Use while True with break for input loops.
  • Keep the body small and clear.
  • Initialize variables before the loop.
  • Prefer for when the number of items is known.

Key points summary

  • The condition is tested before each iteration.
  • The body may run zero times.
  • The update must lead toward False.
  • break exits; continue goes to the next test.
  • else runs only if no break.

Exam and interview points

  • The condition is checked before every iteration.
  • else on while runs if the loop ends without break.
  • Infinite loops come from a missing or wrong update.
  • Python has no do-while statement.

Quick revision

  • while condition: body.
  • Start, test, update.
  • Sentinel stops the loop.
  • break / continue / else.
  • No do-while.

Frequently asked questions

What is an infinite loop?

A loop whose condition never becomes false. It keeps running until you stop the program.

Is while True a bad idea?

No. It is a common pattern if the body has a break that will be reached.

Can a while loop run zero times?

Yes, if the condition is false at the start.

Is there a do-while loop in Python?

No. You can imitate it with while True and a break at the end of the body.

Practise this chapter

17 practice questions Take the chapter quiz

Related chapters