Reputation:
In the official Python documentation, the assignment =
is referred to as a statement or an expression. I really don't get it what it means by assignment is a statement. How is assignment a statement?
Upvotes: 0
Views: 81
Reputation: 780724
A statement is code that tells the computer to do something. A statement has to be written by itself on a line. Examples are assignments, def
to define functions, and while
to start a loop.
An expression is code that calculates a value, and can be used as part of another statement or expression. Examples are arithmetic calculations, function calls, literal values, and comprehensions.
Since assignments are not expressions, you can't use them as part of another statement. For instance, you can't write:
if i = int(input("Enter a number:"))
# do something
You have to do this in two steps:
i = int(input("Enter a number:"))
if i:
# do something
Python 3.8 added a new operator :=
. This is the operator for an assignment expression, described in detail in PEP-572, which can be used as above:
if i := int(input("Enter a number:")):
# do something
Upvotes: 1