繁体   English   中英

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

[英]My elif/else statements in Python are not working

我现在正在学习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语句下的字符串(“不要让所有的em伤害您”或“让地狱离开那里”)。 我也没有任何错误。 为什么是这样?

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

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

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

您正在代码中输入字符串,并且将其与不应做的整数进行比较。 输入您的输入

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM