Python:如果答案不正确,使用类重新询问提示

时间:2016-03-24 02:46:48

标签: python-2.7 class

下面的代码创建了一个名为Luke的英雄。卢克必须选择是否要从他找到的食物中吃苹果或火腿。

如果用户没有选择" apple"或者" ham",我怎样才能让用户重新询问问题以选择" apple"或"火腿"?

我想学习如何在课堂上这样做。我觉得我需要在其他地方的print语句下面做一些事情,但self.food()会导致错误,说str不可调用。

    class Hero():

    def __init__(self, name):
        self.name = name
        self.health = 100   
        self.food = raw_input("You encounter a table full of apples and ham. Which do you eat first? ") 

    def eat(self):  
        x = True
        while x == True:
            if (self.food == 'apple'):
                self.health -= 100
                print "%s has %d health points" % (self.name, self.health)
                x = False
            elif (self.food == 'ham'):
                self.health += 20
                print self.health
                print "%s has %d health points" % (self.name, self.health)
                x = False
            else:
                print "Incorrect. Please try again"
                break

char_1 = Hero("Luke")
char_1.eat()

编辑:

Alex帮助后的变化。

class Hero():

    def __init__(self, name):
        self.name = name
        self.health = 100

    def eat(self):
        while self.health > 0:
            food = raw_input("You encounter a table full of apples and ham. Which do you eat first? ")
            if (food == 'apple'):
                self.health -= 10
                print "%s has %d health points" % (self.name, self.health)
            elif (food == 'ham'):
                self.health += 20
                print self.health
                print "%s has %d health points" % (self.name, self.health)
            else:
                print "Incorrect. Please try again"


char_1 = Hero("Luke")
char_1.eat()

1 个答案:

答案 0 :(得分:0)

使用while循环确保在初始化程序中选择合理的食物,而不是eat方法。 raw_input应位于该循环内,以便用户可以反复输入食物,直到它们正确。关于健康的逻辑可以保留在eat方法中。你也不想break当他们弄错了,你希望循环继续前进,所以删除它。但是,当他们正确而不是设置break时你可以x = False,然后循环可以写成while True: ...,你可以完全摆脱x

顺便说一句,如果您仍在使用x,那么这是一个可怕的变量名称选择。正确的命名是必不可少的,现在就养成正确的习惯。

同样while x == True:是多余的,您只需撰写while x: