while
Python Keywords
Reference ยท while
๐ Looping While a Condition Holds
A for loop is for “do this for each item”; a while loop is for “keep doing this until something changes”. It fits any job where you cannot say in advance how many passes you will need: reading input until it is valid, taking a number apart, working through a queue that may grow, narrowing a search range. This page covers how the condition is tested, what has to change inside the body, compound conditions, while True, the loop else, the walrus operator, and the mistakes that make a loop run forever. Every example below was run, and the output shown is the real output.
while (cond) {} becomes while cond:. Same idea, no parentheses or braces: the colon and the indentation define the block. while True: is while (true). The differences: Python has no do-while (use while True: with a break), no ++ or -- (n += 1), a loop can have an else block, and any value can be a condition (while items: loops while the list is non-empty). The Java idiom while ((line = reader.readLine()) != null) has a direct Python equivalent in the walrus operator: while (line := next_line()) != "":.
while not job_done(): with a short sleep, working through a queue of tasks until it is empty, following a next_page link until there is none, or reading a stream of chunks until it ends. Always give such loops a limit or a timeout: a request handler stuck in a while loop blocks the worker that is serving it.
๐งฐ The Building Blocks
Eight pieces. The first three are the core behaviour, the next four are the variations you will use, and the last one is the mistake to avoid.
while loop only ends if the condition can become false. Whatever the condition depends on has to be updated inside the body, here by n -= 1.0 counts as false, anything else as true. while stack: means “while there is anything left”.and, or and not. This loop stops when either the attempts run out or the thing is found, with no break needed.while True: has no condition of its own, so it needs a break inside (see the break page). Use it when the stopping test fits better in the middle of the body than at the top.while loop may have an else that runs when the condition becomes false. If the loop is left by a break, the else is skipped.:= (Python 3.8 and later) assigns a value and tests it in one go, which suits “read until the end” loops. A plain = in a condition is a SyntaxError.Ctrl+C in the terminal to stop a runaway program. This is the most common while mistake.๐ How It Works, Step by Step
- Python evaluates the condition. If it is false, the loop is over and execution continues after the loop (after its
elseblock, if there is one). - If it is true, the whole indented body runs once.
- Control goes back to step 1 and the condition is evaluated again with whatever values the body has changed.
- A
breakleaves at once, skipping theelse. Acontinuejumps back to step 1 without finishing the body.
When to reach for it: when you cannot say in advance how many passes you need: reading input until it is valid, searching until a limit is reached, shrinking a range, working through a queue that may grow. If you already have a collection or a count to go through, a for loop is usually simpler and cannot get stuck.
๐งช In Context
Seven worked examples, from taking a number apart to a binary search. The last one shows a trap with floating-point numbers.
while. n % 10 is the last digit and n //= 10 removes it. The loop ends when nothing is left.input() inside the loop: without it the condition checks the same bad value forever.break page, but the attempt limit lives in the loop condition, and the else reports the failure. A correct guess still needs a break to leave early.report task adds a new task to the queue, so the number of passes was not known when the loop started. A for loop over a list that is being changed would be fragile; while queue: is not.low <= high says “there is still somewhere to look”. Each pass halves the range, so 100 numbers need at most 7 guesses. The else runs only when the range has run out without finding it.0.1 ten times does not give exactly 1.0, so a loop that waits for x != 1.0 to become false steps over it and keeps going. The steps limit is only there to stop the demonstration. Use < or <= for floats, or count with whole numbers.๐ Quick Reference
| What you want | Write | Notes |
|---|---|---|
| Repeat while a condition is true | while condition: | Checked before every pass, so the body may run zero times. |
| Loop until something inside says stop | while True: + break | Python has no do-while; this is the idiom. |
| Keep going while a collection has items | while items: | Empty list, string, dict, set and 0 are false. |
| Two reasons to stop | while a and not b: | Or use a break for the second reason. |
| Count up or down | n += 1 / n -= 1 | No ++ or -- in Python. |
| Assign and test in one step | while (x := read()) != "": | Walrus operator, Python 3.8+. Plain = is a SyntaxError here. |
| Run something when the condition fails | while ...: ... else: | Skipped if the loop ended with break. |
| Skip to the next pass | continue | Update the loop variable before it, or the loop may never end. |
| Stop a runaway loop | Ctrl+C | In the terminal; raises KeyboardInterrupt. |
| Known number of passes | for i in range(n): | Usually simpler and cannot get stuck. |
A
while loop is only as good as what changes inside it: if the condition depends on a variable, something in the body must update that variable, or the loop runs forever. This is the number-one while bug in every language, but it is easy to hit when you first translate “keep checking” into Python.The update line must be inside the loop: indentation is the block in Python. If
n -= 1 is indented one level too little, it sits after the loop, and the loop body never changes n. There are no braces to show you which block a line belongs to.There is no
do-while: when you need “run once, then test”, write while True: and put an if ...: break where the test belongs, or ask once before the loop and again at the end of the body (as in Example 2).No
++ or --: count++ is a SyntaxError. Write count += 1. And count += 1 is a statement, not an expression, so it cannot go inside the condition; use := if you need to assign there.Never compare floats with
== or != in a loop condition: 0.1 added ten times is 0.9999999999999999, not 1.0, so the loop in Example 7 steps right over its stopping value. Use < or <=, or count whole numbers.Truthiness works differently from Java and JavaScript:
while count: stops when count reaches 0, and while text: stops on an empty string. That is handy for while items:, but if a legitimate value can be 0 or "", test explicitly (is not None, != "").The
else belongs to the loop, not to an if: it runs when the condition becomes false, and is skipped when the loop is left by a break. Java and JavaScript have nothing like it. Read it as “no break”.You cannot put
= in a condition: while x = 5: is a SyntaxError, which protects you from the classic C-style typo, but while x == 5: and while (x := f()) == 5: are fine.