SyntaxError - 不能分配给操作员

Posted

技术标签:

【中文标题】SyntaxError - 不能分配给操作员【英文标题】:SyntaxError - can't assign to operator 【发布时间】:2022-01-10 00:59:11 【问题描述】:
  File "solution.py", line 12
    Rate=8.45 and S=75 and D=tempUnit-150
        ^
SyntaxError: can't assign to operator

完整代码:

tempUnit = int(input())
if tempUnit <= 50:
    Rate = 2.60 and S = 25
    print("Electricity Bill =", tempUnit*Rate + S)
elif tempUnit > 50 and tempUnit <= 100:
    Rate = 3.25 and S = 35 and D = tempUnit-50
    print("Electricity Bill =", 50*2.60+D*Rate+S)
elif tempUnit > 100 and tempUnit <= 200:
    Rate = 5.26 and S = 45 and D = tempUnit-100
    print("Electricity Bill =", 50*2.60+50*3.25+D*Rate + S)
elif tempUnit > 200:
    Rte = 8.45 and S = 75 and D = tempUnit-150
    print("Electricity Bill =", 50*2.60+50*3.25+100*5.26+D*Rte + S)
else:
    print("Invalid Input")

伙计们,我无法解决这里的问题。只是 python 的初学者,将不胜感激。

【问题讨论】:

请分享更多详细信息,例如涉及的代码以及您解决问题的尝试。另外,请标记您正在使用的编程语言 and 的目的是什么?你想执行所有三个任务吗?你可以用分号替换and。 @Mark 或将它们放在单独的行上。 @Ishan,为什么您认为Rate = 2.60 and S = 25 是将这些值分配给这些变量的正确方法? and 是布尔运算符,而不是行分隔符。 我想我只是个笨蛋 【参考方案1】:

您似乎正在尝试比较值,同时也分配它们。 (python 确实为此提供了一个运算符,实际上称为海象运算符,但从外观上看,您似乎只想为变量赋值)。

Rte = 8.45 and S = 75 and D = tempUnit-150

必须是

Rate = 8.45
S = 75
D = tempUnit-150

Rate, S, D = 8.45, 75, tempUnit-150

【讨论】:

成功了。谢谢,伙计【参考方案2】:

and 是一个组合表达式的运算符。

Python 中的赋值是语句

允许链式赋值; a = b = c = d 相当于

a = d
b = d
c = d

从左到右执行分配。

abc 中的每一个都必须是有效目标,而 Rate 是有效目标,而 8.45 and S75 and D 等表达式则不是。

如果要进行三个赋值,只需将它们放在三个单独的语句中即可:

Rate = 8.45
S = 75
D = tempUnit-150

虽然您可以将简单的语句与分号结合起来

Rate = 8.45; S = 75; D = tempUnit - 150

并使用元组(解)打包在单个语句中进行多个赋值

Rate, S, D = 8.45, 75, tempUnit - 150
# Equivalent to
#   t = 8.45, 75, tempUnit - 150
#   Rate, S, D = t

这里都不会被认为是好的风格。

【讨论】:

以上是关于SyntaxError - 不能分配给操作员的主要内容,如果未能解决你的问题,请参考以下文章

SyntaxError:无法分配给函数调用(Python)[关闭]

参数类型“jsObject”不能分配给“buildContext”参数?

不能将属性或索引器“string.this[int]”分配给——它是只读的

参数类型“List<Food>”不能分配给参数类型“Food”Hive db

为啥数组不能分配给Iterable?

最终的局部变量不能分配,不能分配给非最终变量