I am trying to get user input like easy or e equal to E, to choose game modes.
I have tried doing:
difficulty_chooser = input("Welcome to the number game! Choose your difficulty!\n(E)asy, (M)edium, (H)ard: ").lower()
to make it so that if the user types e instead of E, it will show the same output as if E was typed. This does not do anything whatsoever, as when I type e, or any other difficulty modes in lowercase, the code ends.
The code is down below.
def intro():
difficulty_chooser = input(
"Welcome to the number game! Choose your difficulty!\n(E)asy, (M)edium, (H)ard: "
)
if difficulty_chooser == "E":
print("Time for easy mode!")
easy_game()
if difficulty_chooser == "M":
print("Time for a bit of challenge in Medium mode!")
medium_game()
if difficulty_chooser == "H":
print("Time for the biggest challenge!")
hard_game()
CodePudding user response:
Using .upper() will solve the issue, but I figure it's also worth pointing out that if you're trying to handle edge cases then you ought to handle:
- The case when someone enters something other than
E,M, orH(case insensitive). - The fact that all three difficulties will execute sequentially, since you're using
ifas opposed toelifstatements.
Fixing these issues, we get the following code:
def intro():
valid_inputs = {'E', 'M', 'H'}
difficulty_chooser = None
while difficulty_chooser not in valid_inputs:
difficulty_chooser = input(
"Welcome to the number game! Choose your difficulty!\n(E)asy, (M)edium, (H)ard: "
).upper()
if difficulty_chooser not in valid_inputs:
print("Please enter 'E', 'M', or 'H'.")
if difficulty_chooser == "E":
print("Time for easy mode!")
easy_game()
elif difficulty_chooser == "M":
print("Time for a bit of challenge in Medium mode!")
medium_game()
else:
print("Time for the biggest challenge!")
hard_game()
which should be more robust against malformed inputs.
CodePudding user response:
Try to utilize a mapper instead of if-else.
easy_game = medium_game = hard_game = lambda: print('facked starter')
def intro():
choosen_mapper = {'E': easy_game, 'M': medium_game, 'H': hard_game}
prompt_mapper = {'E': "Time for easy mode!",
'M': "Time for a bit of challenge in Medium mode!",
'H':"Time for the biggest challenge!"}
assert choosen_mapper.keys() == prompt_mapper.keys()
difficulty_chooser = None
while difficulty_chooser not in choosen_mapper:
difficulty_chooser = input(
"Welcome to the number game! Choose your difficulty!\n(E)asy, (M)edium, (H)ard: "
).upper()
print(prompt_mapper[difficulty_chooser])
choosen_mapper[difficulty_chooser]()
