【发布时间】:2021-03-11 09:52:32
【问题描述】:
a=5
b=6
a=b+=6
上述语句在 python 中执行时显示语法错误。 为什么会这样? python中不能进行多重复合赋值吗?
【问题讨论】:
标签: python syntax-error operators operator-precedence compound-assignment
a=5
b=6
a=b+=6
上述语句在 python 中执行时显示语法错误。 为什么会这样? python中不能进行多重复合赋值吗?
【问题讨论】:
标签: python syntax-error operators operator-precedence compound-assignment
简短回答:
不,这在 Python 中是不可能的。
长答案:
这是因为 Python 不支持将赋值作为表达式(即 Python 中的赋值不返回值)。
因此,虽然您可能已经习惯在 C 中工作,但由于常见的陷阱,它从来都不是 Python 语言的一部分
...直到去年 Python 3.8 引入了 Walrus 运算符(请参阅此处的文档:https://docs.python.org/3/whatsnew/3.8.html)。
但是,即使使用此运算符,您可以做的最接近的是:
a = (b := 6) - 即没有增量。
【讨论】: