簡體   English   中英

我怎樣才能讓我的代碼正常工作? 用戶輸入不適用於 if、elif 和 else

[英]How can i get my code to work correctly? user input is not working with if, elif, and else

if、elif 和 else 無法正確處理我的輸入。 我正在努力做到這一點,所以你必須通過所有三個問題才能進入我的假俱樂部。 但問題是,如果您錯誤地回答了前兩個問題而正確回答了第三個問題,您仍然可以進入俱樂部。 另外,這是學校的作業,我的老師說我錯過了一個標題,我的 if 語句不包含實際淘汰或接受潛在用戶的邏輯語句。 請幫忙。

def main():
    age = input("are you younger than 21?")
    game = input("what is the game of the day?")
    cool = input("what do you think about school?") 
    
    print("Welcome to Kidz Only.")
    print("are you cool enough to enter?")
    
    if( age == "yes"):
        print("question one is done.")
    if ( game == "super mario bros"):
        print("question two is through.")    
    if ( cool == "i have mixed feelings"):
        print("question three is complete.")
        print("You have passed the quiz. Welcome to Kidz Only!")
        
    else:
        print("Sorry, but you may not enter Kidz Only.")
        
main()

這樣做的原因是因為你說只有當( cool == "i have mixed feelings")然后顯示你被允許加入"cool kids" 您還可以使用and來縮短代碼。

def main():
    age = input("are you younger than 21?")
    game = input("what is the game of the day?")
    cool = input("what do you think about school?") 
    
    print("Welcome to Kidz Only.")
    print("are you cool enough to enter?")
    
    if( age == "yes") and (game == "super mario bros") and ( cool == "i have mixed feelings"):
        print("question three is complete.")
        print("You have passed the quiz. Welcome to Kidz Only!")
        
    else:
        print("Sorry, but you may not enter Kidz Only.")
        
main()

最后一個 if 與 else 語句相關聯,因此即使前兩個錯誤而最后一個正確,它也允許您輸入。 更好的邏輯是為每個要求設置條件。

def main():
    age = input("are you younger than 21?")
    game = input("what is the game of the day?")
    cool = input("what do you think about school?") 
    
    print("Welcome to Kidz Only.")
    print("are you cool enough to enter?")
    
    hasAge = False
    hasGame = False
    hasCool = False

    if( age == "yes"):
        hasAge = True
        print("question one is done.")
    if ( game == "super mario bros"):
        hasGame = True
        print("question two is through.")    
    if ( cool == "i have mixed feelings"):
        hasCool = True
        print("question three is complete.")
        
    if (hasAge and hasGame and hasCool):
        print("You have passed the quiz. Welcome to Kidz Only!")
    else:
        print("Sorry, but you may not enter Kidz Only.")
        
main()

雖然這會導致代碼更冗長,但它可以幫助您更好地查看邏輯

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM