我正在用Python创建一个Yahtzee程序。此函数用于执行用户选择的操作(用户输入一个数字,然后选择适当的列表项)。我刚到了一组数字相加的部分(Yahtzee卡的顶部有1,2等)。我做了一个循环,在列表dicevalues
(一个“掷骰子”数字的随机列表;在程序的前面声明)中每找到一个1
加一个分数。在
我在for 1 in dicevalues:
行得到错误。上面写着SyntaxError: cannot assign to literal
。我查过这个错误,但我搞不懂。我在这里解释的是,程序将为for
中的每个值1
运行代码,但我不太确定是否可以用这种方式使用for
循环。在
def choiceAction():
if options[choice] == "Chance (score total of dice).":
global score
score += (a + b + c + d + e)
if options[choice] == "YAHTZEE!":
score += 50
if options[choice] == "Large straight":
score += 40
if options[choice] == "Small straight.":
score += 30
if options[choice] == "Four of a kind (total dice score).":
score += (a + b + c + d + e)
if options[choice] == "Three of a kind (total dice score).":
score += (a + b + c + d + e)
if options[choice] == "Full house.":
score += 25
if options[choice] == "Add all ones.":
for 1 in dicevalues: # <-- SyntaxError: can't assign to literal
score += 1
是否可能由于某种原因1
不能在for
声明中?在
错误
当您编写
for x in dicevalues:
时,您会迭代dicevalues
,并将每个元素放入变量x
,因此x
不能被1
替换。这就是为什么会出现错误SyntaxError: can't assign to literal
。在解决方案
这里有几种解决方案可以实现您想要的效果:
如果不想使用
dicevalues
中的项,可以使用占位符相关问题 更多 >
编程相关推荐