在python3.6.4中不能赋值给literal

2024-05-29 11:19:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我是python3.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)`

如何消除这个错误?在


Tags: andto代码inyou游戏canprint
2条回答

你的问题是:

2.50 += health

这表示您正试图将2.50 + health分配给一个文本。不能为文本赋值。在

您要做的是将health递增2.50,这可以通过颠倒参数的顺序来完成。在

2.50 += health行改为health += 2.50,代码就可以工作了。在

正如其他人所说,你颠倒了任务的顺序。在

2.50 += health应该是health += 2.50

并且2.50 -= health应该是{}

你也可以优化你的代码一点。在

if yams in ['YES','Yes','yes']:

可以写成

^{pr2}$

lower()将输入字符串转换为小写,这样就不再需要考虑区分大小写了。startswith检查关键字的字符串开头。在

在这种情况下,即使有人说“是的,我会吃一些山药”,你的代码仍然可以接受它作为有效的输入。在

同样地,你也可以对无响应做类似的事情。在

根据@michael_heath的反馈,startswith()如果用户想聪明一点,它可以带来意想不到的结果。一种更简洁、简洁的方式来处理回答是:

if yams.lower() in ('yes','y'):

这样,只接受回答“是”和“Y”,同时考虑大小写敏感度。您可能还需要一个处理程序来处理无效响应。在

相关问题 更多 >

    热门问题