简体   繁体   中英

Why is print(x += 1) invalid syntax?

This works just fine

x = 0
while True:
    x += 1
    print(x)

while this

x = 0
while True:
    print(x += 1)

doesn't

I want a program that counts to infinity or at least until max digits

Because the argument to print() needs to be an expression, and an assignment statement is not an expression.

The walrus operator := was introduced in Python precisely to allow you to do this, though it does not have a variant which allows you to increment something. But you can say

x = 0
while True:
    print(x := x + 1)

This does not strike me as a particularly good or idiomatic use of this operator, though.

Unlike many other languages, where an assignment is an expression and evaluates to the assigned value, in Python an assignment is its own statement. Therefore it can't be used in an expression.

One advantage of this is that if you forget an = in an if statement (ie you meant to write == but wrote = instead) you get an error:

if a = b:   # this is an assignment not a comparison! SyntaxError

In certain other languages this is valid syntactically but wouldn't give you the result you intend, causing hair-loss bugs. (This is one reason linters were invented. The language itself didn't prevent you from making this mistake, so they created an external tool to help with that.)

Python 3.8 adds the assignment operator, := , aka the walrus operator. It behaves like assignment in other languages. So this works:

x = 0
while True:
    print(x := x + 1)

Unfortunately (or fortunately) there is no +:= , which I guess you'd call an augmented walrus.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM