请帮助我编写代码(Python)
为什么当我输入heal时,它也会运行攻击部分?即使我既不键入攻击也不键入治疗,它仍会运行攻击部分。您使用的请帮助我编写代码(Python),python,python-3.x,Python,Python 3.x,为什么当我输入heal时,它也会运行攻击部分?即使我既不键入攻击也不键入治疗,它仍会运行攻击部分。您使用的或是不正确的。就好像你有: import random hp = 100 eh = 100 while hp > 0 and eh > 0: print("Action? (attack, heal, nothing):") act = input(">") attack = random.randint(1, 30) hea
或
是不正确的。就好像你有:
import random
hp = 100
eh = 100
while hp > 0 and eh > 0:
print("Action? (attack, heal, nothing):")
act = input(">")
attack = random.randint(1, 30)
heal = random.randint(1, 15)
if act == "attack" or "Attack":
eh = eh - attack
print(attack)
print("eh = %s" % eh)
elif act == "heal" or "Heal":
hp = hp + heal
print("You have healed %s points" % heal)
print(hp)
任何非空字符串的计算结果均为True
而是使用:
if (act == "attack") or ("Attack"):
甚至:
if act == "attack" or act == "Attack":
在此条件下:
if act in ("attack", "Attack"):
or后面的部分始终计算为true
if act == "attack" or "Attack":
你的意思可能是
>>> if "Attack":
... print "Yup."
...
Yup.
虽然更好的方法是
if act == "attack" or act == "Attack":
eh = eh - attack
print(attack)
print("eh = %s" % eh)
elif act == "heal" or act == "Heal":
hp = hp + heal
print("You have healed %s points" % heal)
print(hp)
首先,我假设if和elif部分缩进以适应while循环 它一直发射攻击部分的原因是你的状况:
if act.lower() == "attack":
它基本上等于
if act == "attack" or "Attack":
这和
if (act == "attack") or ("Attack"):
所以它实际上总是正确的
为了让它工作,你应该在“攻击也”之前重复“act==”部分,这样它就可以工作了
除非我弄错了,否则我认为你的if声明应该是正确的
if act == "attack" or act == "Attack":
eh = eh - attack
print(attack)
print("eh = %s" % eh)
elif act == "heal" or act == "Heal":
hp = hp + heal
print("You have healed %s points" % heal)
print(hp)
事实上,
if act == "attack" or act=="Attack":
将始终评估为true,因此攻击部分将始终运行
我也可以建议你这样做
if "Attack"
通过这种方式,您可以进行单个比较,而忽略区分大小写。只是一个想法。遇到一个有用的:if-act.lower()=“attack”:
它只是Python中的.lower()
而不是.toLower()
if "Attack"
act.toLower() == "attack"