Home > Enterprise >  how to make if/elif/else more efficient
how to make if/elif/else more efficient

Time:12-15

i'm stuck and need a little help. how can i make this more efficient and reduce the number of if/elif/else. i thought to make a function that check the range of an input let's say between 1 to 5 and then return the value to print out what i need. i would love to hear your thoughts on it: there some code:

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:")

CodePudding user response:

Ideally, you check the range of the number in the first loop

Other than that, use a list

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
  • Related