liveBook · Manning

Assignment

As explained in Python Workout, Second Edition

Assignment is the Python operation that binds a value to a name or assigns it to a target.

Assignment stores the result of input in a name, but ordinary assignment is not an expression: it returns no value and cannot directly serve as a while condition. section 2.3

When rewriting an input loop, distinguish these two forms:

  • while s = input(...): is invalid because ordinary assignment produces no value for while to evaluate. section 2.3
  • while s := input(...): uses the walrus operator to assign the input and pass its value to while for Boolean evaluation. section 2.3
  • An empty input string evaluates as False, allowing the loop to exit; the operator remains controversial because shorter code can add complexity and bugs. section 2.3
while s = input('Enter thoughts:'):
    print(f'Your thoughts are: {s}')

Compare the tempting ordinary-assignment loop with the working assignment-expression version. section 2.3

while s := input('Enter thoughts:'):
    print(f'Your thoughts are: {s}')

Use the walrus form when one condition must both capture input and test its value. section 2.3

How Python Workout, Second Edition covers it

How deep it goes
Explains assignment’s expression behavior, demonstrates the walrus alternative, and stops short of broader syntax or implementation details.
Examples
Uses an input-reading while loop, contrasting invalid ordinary assignment with a working walrus expression.
What it assumes
Assumes familiarity with while loops, input, and Boolean evaluation while clarifying why assignment cannot return a value.
What you can do after
Apply assignment expressions to combine input capture and loop testing while recognizing when ordinary assignment is invalid.
How it connects
Connects assignment with expressions, Boolean evaluation, while loops, input, and the walrus operator.

Also explained in

Compare how 7 books explain assignment →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python Workout, Second Edition. The section links point to the parts of the book it draws on.