简体   繁体   English

为什么 print(x += 1) 语法无效?

[英]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.因为print()的参数需要是一个表达式,而赋值语句不是表达式。

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.海象运算符:=是在 Python 中引入的,正是为了允许您执行此操作,尽管它没有允许您增加某些内容的变体。 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.与许多其他语言不同,其中赋值是一个表达式并计算为指定的值,在 Python 中,赋值是它自己的语句。 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语句中忘记了= (即您打算写==但写了= ),您会得到一个错误:

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.) (这是 linter 被发明的原因之一。语言本身并不能阻止你犯这个错误,所以他们创建了一个外部工具来帮助解决这个问题。)

Python 3.8 adds the assignment operator, := , aka the walrus operator. Python 3.8 添加了赋值运算符:= ,又名海象运算符。 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.不幸的是(或幸运的是)没有+:= ,我猜你会称之为增强型海象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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