当用户输入food ='苹果'健康时,在我的循环中,它将持续到3次,我想在健康变为0 0r小于0时退出循环。<<
我如何解决退出循环之外的问题,但继续剩下的程序?
print("Let us play a game")
class Hero():
def __init__(self, heroName):
self.heroName = heroName
self.health = 100
def game(self, food):
if food == 'Apple':
print("Hero is dead")
self.health = self.health - 100
#something to do here I think
elif food == 'Banana':
self.health +=30
elif food == 'Pear':
self.health -= 40
else:
print("We are strict to our rules You just got 3 choices")
x = input("Press <A> to continue")
if x == 'a':
name = input("Enter Your Name")
print("Welcome!",name, " You can Play An Intersting Game")
heroName = input(" What name do you want to give your hero")
hero = Hero(heroName)
print("Ok, Your Hero is ", hero.heroName)
print("Now lets paly the game...nn You have three choices to food your
hero (i) Apple (ii) Banana (iii) Pearnn")
i = 0
while i < 3:
food = input("What You want your hero to feed")
hero.game(food)
print("Life of",hero.heroName,"is",hero.health)
i +=1
sth = input("Press anykey and then hit <ENTER> to exit...")
当英雄的健康为 <= 0
时,您应该break
。添加
if hero.health <= 0:
break
在循环中的合适位置。
类似的东西:
只需退出循环含义
while something:
if self.health <= 0:
break
退出功能并继续使用程序
while something:
if self.health <= 0:
break
call_hero()
print "Let us play a game"
class Hero():
def __init__(self, heroName):
self.heroName = heroName
self.health = 100
def game(self, food):
if food == 'Apple':
print"Hero is dead"
self.health = self.health - 100
elif food == 'Banana':
self.health +=30
elif food == 'Pear':
self.health -= 40
else:
print "We are strict to our rules You just got 3 choices"
x = raw_input("Press 'a' to continue")
if x == 'a':
name = str(raw_input("Enter Your Name"))
print "Welcome!",name, " You can Play An Intersting Game"
heroName =str(raw_input(" What name do you want to give your hero"))
hero = Hero(heroName)
print "Ok, Your Hero is ", hero.heroName
print "Now lets paly the game...nn You have three choices to food your
hero (i) Apple (ii) Banana (iii) Pearnn"
i = 0
else:
print "entry not allowed"
i=4
while i < 3:
food=str(raw_input("What You want your hero to feed"))
hero.game(food)
if hero.health<1:
i=i+4
else:
print "Life of",hero.heroName,"is",hero.health
i +=1
sth = str(raw_input("Press anykey and then hit <ENTER> to exit..."))
您可以使用此代码来学习并使您的有趣游戏来解决问题。