簡體   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