簡體   English   中英

如何使 if/elif/else 更高效

[英]how to make if/elif/else more efficient

我被困住了,需要一點幫助。 我怎樣才能提高效率並減少 if/elif/else 的數量。 我想制作一個 function 來檢查輸入的范圍,比如說在 1 到 5 之間,然后返回值以打印出我需要的內容。 我很想聽聽你的想法:有一些代碼:

while True:
    difficulty = input("Please choose also the game difficulty from 1 to 5: ")
    if not difficulty.isdigit():
        print("Please enter a valid number: ")
    else:
        break

while True:
    if difficulty == "1":
        print("Level of difficulty is very easy, ok you are scared to loose but let's play.")
        break
    elif difficulty == "2":
        print("Level of difficulty is  easy, ok let's play.")
        break
    elif difficulty == "3":
        print("Level of difficulty is normal, ok let's play.")
        break
    elif difficulty == "4":
        print("Level of difficulty is hard, now we are talking let's play.")
        break
    elif difficulty == "5":
        print("Level of difficulty is very hard, ok we got a challenger let's play.")
        break
    else:
        difficulty = input("You chose an invalid number, choose between 1 - 5. Try again:")

理想情況下,您檢查第一個循環中的數字范圍

除此之外,使用列表

descriptions = [
    "very easy, ok you are scared to loose but let's play.", 
    "easy, ok let's play."
]

while True:
     i = int(difficulty) - 1
     if i not in range(5):
         # invalid input, get it again 
         difficulty = input("must be between 1 and 5: ")
         continue 
    lines() 
    print("Level of difficulty is " + descriptions[i]) 
    break

暫無
暫無

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

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