Skip to content
Tutorials Center
My learning

Topics

Lesson 24 of 149 Β· Control Flow

while Loops

Learn how Python while loops repeat code while a condition is true. Validate input, use sentinel values, write while True loops and avoid accidental infinite loops.

A for loop runs once per item in a collection, so you know in advance how many times it will repeat. Many problems don't work that way. A game keeps going until the player quits. A program keeps asking for a password until it gets a valid one. A savings plan grows until it reaches a target, and you don't know how many months that takes. For these, Python offers the while loop.

A while loop repeats its body as long as a condition stays true. It checks the condition before every iteration, and the moment the condition is false, the loop stops. In this lesson you'll write condition-driven loops, read input until a stop word, use the while True pattern, and learn how to make sure your loops always end.

How a while loop works

The syntax mirrors an if statement, but the body can run many times:

Python
while condition:
    body

Python follows these steps:

  1. Evaluate the condition.
  2. If it's falsy, skip the body and continue after the loop.
  3. If it's truthy, run the body once, then go back to step 1.
Python A countdown

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Three ingredients make this loop work, and every counting while loop needs all three:

  • Setup: seconds = 5 gives the condition something to check.
  • Condition: seconds > 0 decides whether to run the body again.
  • Progress: seconds -= 1 changes the state so the condition eventually becomes false.

If the condition is false from the very start, the body never runs at all. Change seconds = 5 to seconds = 0 and run it again: you'll see only "Liftoff!".

When you don't know the number of steps

The countdown above could have been a for loop over range(). A while loop shines when the number of iterations depends on what happens inside the loop. Here's a classic: how many years does it take for money to double at a given interest rate?

Python Doubling an investment

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Nobody told the loop to run 12 times. It ran until the balance crossed the target. Try changing rate to 0.03 or 0.10 and see how the answer changes.

Another example with an unknown number of steps is the famous Collatz sequence: start from any positive whole number; if it's even, halve it; if it's odd, triple it and add one. Mathematicians believe you always reach 1 eventually, but nobody has proved it.

Python The Collatz sequence

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Reading input until a sentinel

A sentinel is a special value that means "stop". Programs that read a stream of data often loop until they see it. In the editor below, the Input box already contains a few lines; each input() call reads the next one.

Python Summing until 'done'

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Notice that input() appears twice: once before the loop to get the first value, and once at the end of the body to get the next. That duplication is a bit clumsy, and it's easy to forget the second call. The next pattern removes it.

The while True pattern

Writing while True: creates a loop whose condition never becomes false on its own. You end it from inside the body with break, which exits the loop immediately. You'll study break in detail in break, continue and Loop else; here's the idea:

Python Input validation with while True

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The loop asks once per iteration, rejects bad answers with continue (which jumps straight back to the top of the loop), and leaves with break as soon as the answer is valid. Because the input() call appears only once, this is the most popular way to write "ask until valid" in Python. Edit the Input box to try other values.

Note: "-4".isdigit() is False, because the minus sign isn't a digit. That's why the second attempt is rejected before the range check runs.

Combining the condition with the walrus operator

The walrus operator := assigns a value and uses it in the same expression. It lets you fold the "read, then test" step into the loop header:

Python Sentinel loop with :=

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Each iteration calls input(), stores the result in color and compares it with "stop", all in the header. (A blank line, != "", is another popular sentinel in terminal programs.) The parentheses around the assignment are required. This style is compact; use it when it reads clearly, and fall back to while True with break when the logic gets longer.

Avoiding infinite loops

An infinite loop is a loop whose condition never becomes false and that has no break. It's the most common while bug. Typical causes:

  • Forgetting the progress step, for example leaving out seconds -= 1.
  • Updating the wrong variable, such as incrementing count while the condition checks i.
  • A condition that skips past its target, like while x != 10 when x goes up by 3 from 0 (0, 3, 6, 9, 12, …) and never equals 10. Prefer < or > over != when counting.
  • Floating-point comparisons: while x != 1.0 with x += 0.1 may never hit exactly 1.0, because decimals like 0.1 can't be stored exactly.

Warning: In a terminal, you stop a runaway Python program with Ctrl + C. In the editors on this site, press Stop, or wait: each run is cut off after 30 seconds.

When you're unsure whether a loop will end, add a safety limit while developing:

Python A loop with a safety limit

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The else attached to the loop runs only if the loop ended without break. That's a lesser-known feature you'll explore in the next lesson.

for or while?

Both loops can often solve the same problem, but one usually fits better:

Use for when… Use while when…
You're processing every item of a collection You repeat until something happens
The number of iterations is known up front The number of iterations depends on the work done
You'd otherwise manage an index by hand You're waiting for valid input or a sentinel

A good rule of thumb: if you find yourself writing i = 0, while i < len(items) and i += 1, switch to for item in items. It's shorter and can't loop forever.

Check your understanding

Quick check Β· 5 questions

of 5 answered You scored / 5 Β· perfect!

  1. 1. How many times does the body of while n < 3 run if n starts at 5?

    The condition is checked before the first iteration. 5 < 3 is false, so the body never runs.
  2. 2. What is missing from this loop? i = 0 then while i < 5: with the body print(i)

    Without progress, i stays 0, the condition stays true and the loop runs forever.
  3. 3. In a while True: loop, which statement ends the loop?

    break exits the loop immediately. continue jumps back to the top of the loop, pass does nothing, and stop isn't a Python keyword.
  4. 4. Why might x = 0 followed by while x != 10: with x += 4 in the body never end?

    The value jumps past 10. A condition like while x < 10 is safer when counting.
  5. 5. What is a sentinel value?

    Sentinels such as "done", an empty string or -1 tell a loop that reads data when to stop.

Summary

  • while condition: repeats its body as long as the condition is truthy, checking it before each iteration.
  • A counting while loop needs setup, a condition and progress toward making the condition false.
  • Use while when the number of iterations depends on the work: reaching a target, reading until a sentinel, validating input.
  • while True: plus break is the standard "ask until valid" pattern; continue restarts the loop early.
  • The walrus operator can read and test in one header: while (line := input()) != "stop":.
  • Guard against infinite loops: always make progress, prefer </> over !=, and add a safety limit when unsure.

Next: break, continue and Loop else, where you'll take fine control of when loops skip and stop.