Home > Software engineering >  Can an input accept 1 OR 2 variables depending on what the user types?
Can an input accept 1 OR 2 variables depending on what the user types?

Time:06-15

I'm doing a memory game and I'm using a function to set the coordinates for the player. The user can type two numbers (like 0,1 or 5,3). But I want to be possible for the user to type M to see the board again and Z to give up. Can I do that with only one function?

def first_player_input():
    x, y = input("Enter the desired coordinates: ").split(",")
    return x, y

CodePudding user response:

I'm guessing your current code structure is roughly akin to the following:

def first_player_input():
    x, y = input("Enter the desired coordinates: ").split(",")
    return x,y

...

#later on in the code
x, y = first_player_input()

However, this is an unnecessary level of abstraction. What about you do something like the following instead?

...
first_player_input=input("Enter the desired coordinates: ")
if first_player_input == 'M':
    #do stuff here letting the player see the board again
    ...
elif first_player_input == 'Z':
    #let the player give up here
    ...
else: #x,y input
    x, y = first_player_input.split(",")
    #handle x and y here
    ...

The reason I'm suggesting this is that if you put it all in one function, you'll need to typecheck and then value check the result of that function anyway, which is effectively going to introduce double the number of if statements and hence the code complexity.

CodePudding user response:

Certainly - just check before splitting!

def first_player_input():    
    value = input("Enter the desired coordinates (or M or Z): ")
    if "M" in value:
        handle_M()
    elif "Z" in value:
        handle_Z()
    elif "," in value:
        return value.split()
    raise ValueError(f"improper input: {value}")

Additionally, you expect troublesome inputs (ie. what if they provided non-ints or three values separated by commas?), consider a regular expression to reject them

    if not re.match(r"^(\d ,\d |M|Z)$", value)
        raise ValueError("expected two ints or M or Z")
  • Related