Assignment expressions
Before we look at some more complicated examples, we would like to briefly introduce you to a relatively new feature that was added to the language in Python 3.8, via PEP 572 (https://www.python.org/dev/peps/pep-0572). Assignment expressions allow us to bind a value to a name in places where normal assignment statements are not allowed. Instead of the normal assignment operator =
, assignment expressions use :=
(known as the walrus operator because it resembles the eyes and tusks of a walrus).
Statements and expressions
To understand the difference between normal assignments and assignment expressions, we need to understand the difference between statements and expressions. According to the Python documentation (https://docs.python.org/3/glossary.html), a statement is:
…part of a suite (a "block" of code). A statement is either an expression or one of several constructs with a keyword, such asif
,while
or...