变量更改给我语法错误“无法分配给运算符”

时间:2018-01-21 16:10:56

标签: python

我在一个名为'repl.it'的网站上用Python编写基于文本的游戏,在尝试更改变量时,我遇到了这个错误:

Traceback (most recent call last):
  File "python", line 526
SyntaxError: can't assign to operator

我是python的新手,我无法理解,所以我只是希望有人修改代码并告诉我这是如何工作的。

以下是代码:

#Adding hits or misses
if decision == "t3" : mothershiphit = mothershiphit + 1
elif decision == "t2" : jetdown = jetdown + 1
else: mothershipmiss = mothershipmiss + 1, mothershiplanded = mothershiplanded + 1

print " "

Link to the game:尚未完成,但我会继续努力。

1 个答案:

答案 0 :(得分:1)

不使用逗号(,),而是使用分号(;)将语句分隔在一行中。

if decision == "t3": mothershiphit = mothershiphit + 1
elif decision == "t2": jetdown = jetdown + 1
else: mothershipmiss = mothershipmiss + 1; mothershiplanded = mothershiplanded + 1

<强>解释

使用逗号,解释器会认为正在执行以下操作:

mothershipmiss + 1, mothershiplanded = mothershiplanded + 1

正如您所看到的,在第一行中,您实际上将+ 1添加到运算符(左侧是什么),这是无效的。

使用分号,语句将如下所示:

mothershipmiss = mothershipmiss + 1
mothershiplanded = mothershiplanded + 1

这是有效的,因为你正在为右边的元素分配1。

相关问题