October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PCOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk2 min

How to Use Assignment in a Python while Loop

Use Python’s := assignment expression in a while condition to save and test a value in one step. See the file-reading pattern, stopping rules, and common mistakes.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

In Python 3.8 and later, use the assignment expression := in a while condition when the value you calculate or fetch is also needed inside the loop. For example, while chunk := file.read(9000): reads a chunk, assigns it to chunk, and continues while that result is truthy.

How assignment works in a while condition

The general form is while name := expression:. Python evaluates the expression, assigns its result to name, and uses that same result as the condition. The loop body runs when the result is true; it stops when the result is false. Python calls := an assignment expression, also known as a named expression or informally the walrus operator. Python 3.14.7 language reference: expressions

Unlike an ordinary assignment statement, an assignment expression produces a value. This lets the condition both save a result and test it without repeating the calculation or operation.

Read a file until it reaches the end

Python’s language reference uses this pattern to process a file in chunks:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
while chunk := file.read(9000):
    process(chunk)

Before each iteration, file.read(9000) is called and its result is assigned to chunk. A non-empty chunk is truthy, so the body processes it. When the read returns an empty result at the end of the file, the condition is false and the loop ends. The number 9000 is the read size in this example, not a special requirement of assignment expressions. Python 3.14.7 language reference: expressions

Equivalent expanded form

You can write the same basic control flow without an assignment expression:

while True:
    chunk = file.read(9000)
    if not chunk:
        break
    process(chunk)

The compact version keeps the read and its termination check together. The expanded version can be easier to understand when the stopping logic has several branches, or when the loop needs additional cleanup or error handling. These are readability trade-offs, not different Python semantics.

Choose a condition that matches the data

The assignment-expression form uses the assigned value itself as the condition. Empty strings, empty containers, zero, and None are false in Python, so a bare condition is useful when one of those values means “stop.” If a falsey value is valid data, it will stop the loop too early; test the actual end condition instead.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

For example, if zero is valid and only None signals that there is no next value, make that test explicit:

while (value := get_next_value()) is not None:
    process(value)

Parentheses make the assignment expression’s scope clear in this more complex condition. They are optional around a named expression in an if or while statement, but may help readability. Python 3.14.7 language reference: expressions

Common syntax and control-flow mistakes

  • Using = instead of :=. A regular assignment statement such as while chunk = file.read(9000): is not valid syntax. Use := to assign and return a value in the condition.
  • Confusing assignment with comparison. := assigns a value; == compares two values.
  • Forgetting what makes the loop stop. A while condition is checked before each iteration, and the body repeats while it is true. Ensure the operation can produce a false result or add an explicit stopping test. Python 3.11.17 language reference: compound statements
  • Misreading while ... else. A loop’s optional else suite runs when its condition becomes false; it does not run if the loop exits with break. Python 3.11.17 language reference: compound statements
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Python version requirement

Assignment expressions were introduced in Python 3.8, so code using := requires Python 3.8 or later. The feature is described in PEP 572 and documented in the current language reference.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Outdated Drivers Are Slowing You DownFree scan - exact matches
Windows Errors? Fix Them Before They SpreadFree repair scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.