Python 3.6.4中“Can't assign to literal”错误的解决方法
解决Python中的"can't assign to literal"错误
嘿,我来帮你搞定这个报错!你遇到的can't assign to literal错误其实很好理解——Python里赋值操作的左边必须是一个变量,而你现在把固定的数值字面量(比如2.50)放在了赋值运算符的左边,这就好比你想把水倒进一个写着“2.5”的牌子里,而不是一个杯子,当然行不通啦。
看你代码里的这两行:
2.50 += health # 还有下面的 2.50 -= health
这完全搞反了逻辑!你是想修改health变量的值,应该把变量放在左边,数值放在右边,正确的写法是:
health += 2.50 # 等同于 health = health + 2.50 # 和 health -= 2.50 # 等同于 health = health - 2.50
另外,你的代码还有缩进问题——if和elif块里的代码需要缩进(通常是4个空格),不然Python会认为这些代码不在条件判断里,导致语法错误。
修正后的完整代码如下:
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() health += 2.50 print('Those yams were very nutritious and you felt more active.') print(health) elif yams in ['NO','No','no']: health -= 2.50 print('You missed a chance to be healthier.') print(health)
最后给你一个小优化建议:可以把用户输入统一转成大写(或小写),这样判断逻辑更简洁,不用罗列所有大小写组合,比如:
yams = input('Will you eat them?: ').upper() if yams == 'YES': # ... 后续代码 elif yams == 'NO': # ... 后续代码
内容的提问来源于stack exchange,提问作者The Weird
相关产品推荐
相关产品推荐

