简体   繁体   English

语法错误:“无法分配给运算符” Python

[英]Syntax error: “cant assign to operator” Python

a, b, c = 0, 1,0
while c < 1000000:
    print (b)
    a, b = b, a + b, c = c + b

The interpreter throws me the "can't assign to operator" error. 解释器向我抛出“无法分配给操作员”错误。 Ninja IDE highlights the variable initialisation to be the problem. Ninja IDE突出显示了变量初始化问题。 However when I run the code in the interpreter, the "a + b" is highlighted as the problem part. 但是,当我在解释器中运行代码时,“ a + b”被突出显示为问题部分。 Can you help me identify the issue i'm having? 您能帮我确定我遇到的问题吗?

when you write a, b, c = 0, 1, 0 , you are not creating multiple assignments. 当您编写a, b, c = 0, 1, 0 ,您并没有创建多个分配。 Instead, you implicitly use tuple packing and unpacking . 取而代之的是,您隐式使用元组装箱拆箱 In the line a, b = b, a + b, c = c + b , you are trying to do the same but the right part of the assignment contains another assignment, which is invalid (in python an assignment is not an expression). a, b = b, a + b, c = c + b ,您尝试执行相同的操作,但赋值的右侧包含另一个赋值,该赋值无效(在python中,赋值不是表达式) 。 If you want to write it in one line, you should write 如果要一行写,应该写

a, b, c = b, a + b, a + b + c

However, since the value of c relies on the value of b having changed, it is probably clearer to split it into two lines 但是,由于c的值依赖于已更改的b的值,因此将其分为两行可能更清楚

a, b = b, a + b
c = c + b

Similar to how a, b, c = 0, 1,0 works... 类似于a, b, c = 0, 1,0工作方式...

This line is trying to assign a and b to the right hand side of the equals. 该行试图将a和b分配给等号的右侧。 You've got three things over there, and one of those is a variable assignment operation 您在那儿有三件事,其中之一是变量赋值操作

a, b = b, a + b, c = c + b

Maybe you meant this instead 也许你是这个意思

a, b,c = b, a + b, c + b

Or, of course, just do it on multiple lines 或者,当然,只需多行

Its a simple fix: change where the c = c + b is in your code. 这是一个简单的解决方法:更改代码中c = c + b位置。

a, b, c = 0, 1,0
while c < 1000000:
    print (b)
    a, b, c = b, a + b, c + b

What it's doing is: 它正在做什么:

a = b
b = a+b
c = c+b

But you can write it in separate lines. 但是您可以将其写在单独的行中。

Hope that helps 希望能有所帮助

The variables BEFORE the "=" sign will be interpreted as the variable that you are going to store on. 符号“ =”之前的变量将被解释为要存储的变量。 The data AFTER the "=" sign will be interpreted as the data that you are going to store in the variable you just created in the left side with respect to the same position. 符号“ =”之后的数据将被解释为要存储在刚创建的变量中相对于同一位置的变量中。

Example: 例:

a,b = 5,10
print(a)
#Outputs 5
print(b)
#Outputs 10

Since you only have two variables before the "=" sign, there will be only two container for the data you just type after the "=" sign which is b and a+b 由于在“ =”符号之前只有两个变量,因此在“ =”符号之后键入的数据只有两个容器,即b和a + b

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

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