Just a beginner question about good practice.
Take this bit of code for example. I want a particular user input, and if they enter something crazy, I obviously want to run the code inside the function again.
def get_difficulty():
chosen_difficulty = str(raw_input("*** Choose difficulty: Easy, Medium or Hard: ").lower())
if chosen_difficulty == "hard":
return 10
elif chosen_difficulty == "medium":
return 15
elif chosen_difficulty == "easy":
return 20
else:
print "*** Did you enter 'Easy', 'Medium' or 'Hard'?"
print "*** Sorry that was passive aggressive. You obviously didn't..."
return get_difficulty()
Is it ok to make the function handle the else case like this? It seems inelegant; if the person entered something wrong five times the function would be nested 5 times and eventually the right answer would have to cascade down through the return of each function.
It works fine, but is there a better way?