示例:当我输入时,我试图从Hero.checkLife获取print语句进行打印1.我做了一些测试,看起来它正确获取输入但只是跳过if / elif语句。不知道为什么,任何提示将不胜感激。 python中的格式是正确的,但复制到这里并没有超级顺利。
class Hero:
life = 200
def checkLife(self):
if self.life <= 0:
print("Oh no! Hero has fallen")
else:
print("Hero has " + str(self.life)+ " life!")
def attackedByEnemy(self):
self.life -= 45
class Enemy:
life = 115
def checkLife(self):
if self.life <= 0:
print("Enemy has fallen!")
else:
print("Enemy has " + str(self.life)+ " life!")
def attakedByHero(self):
self.life -= 55
hero = Hero()
enemy = Enemy()
while Enemy.life > 0:
action = input("Enter attack. \n 1. Check Hero life \n 2. Check
Enemy life \n 3. Attack the enemy \n 4. Attack the hero \n")
if action == 1:
hero.checkLife()
elif action == 2:
enemy.checkLife()
elif action == 3:
enemy.attakedByHero()
elif action == 4:
hero.attackedByEnemy()
答案 0 :(得分:1)
正如roganjosh在评论中所述,这里的问题是input()
函数返回一个字符串,而不是一个整数(这是if
/ elif
语句检查的内容)。要解决此问题,请将输入结果转换为如下所示的整数:
action = int(input("""Enter attack. \n 1. Check Hero life \n 2. Check
Enemy life \n 3. Attack the enemy \n 4. Attack the hero \n"""))