我在Python中的elif / else语句不起作用

时间:2015-07-28 04:07:00

标签: python python-2.7 if-statement

我正在学习python,这是我到目前为止的代码,就像有条件的一点点练习一样:

def the_flying_circus():
    animals = raw_input("You are the manager of the flying circus. Which animals do you select to perform today?")
    if animals == "Monkeys":
        num_monkeys = raw_input("How many monkeys are there?")
        if num_monkeys >= 20:
            return "Don't let all of 'em hurt you!"
        elif num_monkeys < 20 and num_monkeys >= 5:
            return "Not too many, but be careful!"
        elif num_monkeys < 5:
            return "You're in luck! No monkeys to bother you."
    elif animals == "Anteaters":
        return "What the hell kinda circus do you go to?!"
    elif animals == "Lions":
        height_lion = raw_input("How tall is the lion (in inches)?")
        if height_lion >= 100:
            return "Get the hell outta there."
        elif height_lion < 100:
            return "Meh. The audience usually has insurance."
    else:
        return "Dude, we're a circus, not the Amazon rainforest. We can only have so many animals."
print the_flying_circus()

所以我遇到的问题是代码工作正常,直到我进入动物之后。如果我做食蚁兽,那很好。但是如果我做猴子或狮子,无论我输入什么数字,只会打印出初始if语句下的字符串(&#34;不要让所有的人伤害你&#34;或者#34;在那里得到地狱&#34;)。我也没有收到任何错误。这是为什么?

3 个答案:

答案 0 :(得分:3)

num_monkeys = raw_input("How many monkeys are there?")

raw_input会返回一个字符串,您需要将其转换为int

num_monkeys = int(raw_input("How many monkeys are there?"))

答案 1 :(得分:1)

您正在代码中输入一个字符串,并将其与一个不应该完成的整数进行比较。输入你的输入

num_monkeys=int(raw_input("Write your content here"))

答案 2 :(得分:1)

raw_input将输入作为字符串。它应该转换为int

def the_flying_circus():
    animals = raw_input("You are the manager of the flying circus. Which animals do you select to perform today?\n")
    if animals.lower() == "monkeys":
        num_monkeys = int(raw_input("How many monkeys are there?\n"))
        if num_monkeys >= 20:
            result = "Don't let all of 'em hurt you!\n"
        elif num_monkeys < 20 and num_monkeys >= 5:
            result = "Not too many, but be careful!\n"
        elif num_monkeys < 5:
            result = "You're in luck! No monkeys to bother you.\n"
    elif animals.lower() == "anteaters":
        result = "What the hell kinda circus do you go to?!\n"
    elif animals.lower() == "lions":
        height_lion = int(raw_input("How tall is the lion (in inches)?\n"))
        if height_lion >= 100:
            result = "Get the hell outta there.\n"
        elif height_lion < 100:
            result = "Meh. The audience usually has insurance.\n"
    else:
        result = "Dude, we're a circus, not the Amazon rainforest. We can only have so many animals.\n"
    return result

result = the_flying_circus()
print result