-2

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 difficulty from 1 to 3: ")
    if not difficulty.isdigit():
        print("Please enter a valid number: ")
    else:
        break

while True:
    if difficulty == "1":
        print("Level of difficulty is very easy.")
        break
    elif difficulty == "2":
        print("Level of difficulty is  easy.")
        break
    elif difficulty == "3":
        print("Level of difficulty is normal.")
        break
    else:
        difficulty = input("You chose an invalid number, choose between 1 - 3. Try again:")
Flav
  • 5
  • 3

1 Answers1

0

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
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245