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

2024-04-25 23:40:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我现在正在学习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语句首字母下面的字符串(“不要让它们伤害你”或“滚出去”)。我也没有收到任何错误。为什么会这样?在


Tags: thetoyouinputrawreturnifnum
3条回答
num_monkeys = raw_input("How many monkeys are there?")

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

^{pr2}$

原始输入将输入作为字符串。它应该转换成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

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

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

相关问题 更多 >