我是python 3.6.4的新手,我正在尝试制作游戏,但它说的是can't assign to literal
。
这是我的代码:
`health = 5.0
print('You keep on exploring, and you find a patch of ice yams in the snow.')
yams = input('Will you eat them?: ')
if yams in ['YES','Yes','yes']:
print()
2.50 += health
print('Those yams were very nutritious and you felt more active.')
print(health)
elif yams in ['NO','No','no']:
2.50 -= health
print('You missed a chance to be healthier.')
print(health)`
如何摆脱这个错误?
答案 0 :(得分:4)
正如其他人所说,你颠倒了作业的顺序。
2.50 += health
应为health += 2.50
和2.50 -= health
应为health -= 2.50
您也可以稍微优化您的代码。
if yams in ['YES','Yes','yes']:
可以写成
if yams.lower().startswith('yes'):
lower()
将您的输入字符串转换为小写,因此区分大小写不再是一个问题。 startswith
检查关键字字符串的开头。
在这种情况下,即使有人说“我会吃一些山药”,你的代码仍然可以接受它作为有效的输入。
同样,你可以为No response做类似的事情。
Per @ michael_heath的反馈,startswith()
如果用户想要了解它,可能会引入意想不到的结果。处理响应的更简洁方法是使用:
if yams.lower() in ('yes','y'):
这种方式只接受响应“是”和“Y”,同时考虑了区分大小写。您可能还希望拥有无效响应的处理程序。
答案 1 :(得分:2)
您的问题在于:
2.50 += health
这表示您正在尝试将2.50 + health
分配给文字。您无法为文字指定值。
您要做的是将health
增加2.50
,这可以通过颠倒参数的顺序来完成。
将行2.50 += health
更改为health += 2.50
,您的代码将有效。