How to deal with unrecognized user inputs in match/case --Python

176 Views Asked by At

I'm working on a text-based game in Python and basically it's a series of functions that store match/case statements where the player can type things in to select different choices, which then bring the player to different functions. The problem is that a simple typo can quit the game or jump to a random function. The simple solution to this would be the example code I have pasted below, where a case_: statement catches the unrecognized inputs, but I have over 100 functions and I was hoping I would not have to add this manually for each one.

Is there any way I could have some globally defined property where if an input is not recognized from the options given (i.e., the other cases), the user is taken back to the start of that function where they can try again?

Example code:

def examplechoice():
    response = input("What is your favorite season?\n")
    match (response.lower()):
        case "winter":
            print("some function here")
        case "spring":
            print("some function here")
        case "summer":
            print("some function here")
        case "fall":
            print("some function here")
        case _:
            print("response not recognized--try again")
            examplechoice()
1

There are 1 best solutions below

0
Ted Nguyen On

You can use a simple while True loop with break. The loop will go on forever until you enter the right season. Just need a little modification to your code.

def examplechoice():
    while True:
        response = input("What is your favorite season?\n")
        match (response.lower()):
            case "winter":
                print("some function here")
                break
            case "spring":
                print("some function here")
                break
            case "summer":
                print("some function here")
                break
            case "fall":
                print("some function here")
                break
            case _:
                print("response not recognized--try again")

examplechoice()