Home > database >  If a user enters an invalid string option in python how should I handle the exception?
If a user enters an invalid string option in python how should I handle the exception?

Time:11-29

I'm writing a rock, paper, scissors, game for a user and computer and I want the user to type in one of the three options i.e "rock" but I'm not sure what kind of exception to use if the user enters say "monkey."

class RockPaperScissors:
    def getUserChoice(userchoice):
        while True:
            try:

                userchoice = input("Type in your choice: rock, paper, scissors: ")
                if userchoice != "rock" or userchoice != "paper" or userchoice != "scissors":
                    raise ValueError("Try typing in your choice again")
                break
            
            except:
                print("Invalid Input.")   
        return userchoice.lower()

CodePudding user response:

It's very helpful to use a sentinel value like None, if you want to remind the user of the input choices after each failed attempt:

class RockPaperScissors:

    def getUserChoice(self):
        choice = None
        while choice not in ('rock', 'paper', 'scissors'):
            if choice is not None:
                print('Please enter only rock, paper, or scissors.')
            choice = input('Type in your choice: rock, paper, scissors: ').lower()
        return choice

You can also do an even shorter version in later versions of Python:

class RockPaperScissors:

    def getUserChoice(self):
        prompt = 'Type in your choice: rock, paper, scissors: '
        choices = 'rock', 'paper', 'scissors'
        while (choice := input(prompt).lower()) not in choices:
            print('Please enter only rock, paper, or scissors.')
        return choice

CodePudding user response:

In this case, you probably do not need an exception.
You probably want to loop again on input().
The following code is more explicit:

class RockPaperScissors:
  def getUserChoice():
    while True:
      userchoice = input("Type in your choice: rock, paper, scissors: ").lower()
        if userchoice in ( "rock", "paper" "scissors"):
          return userchoice
        else:
          print( "Invalid input. Try again.)

The try|except mechanism is more appropriate when you want to handle the error at an upper level.

CodePudding user response:

Another option is to have the user enter a number. That way, you don't have to worry about spelling:

class RockPaperScissors:
    def getUserChoice(options = ("rock", "paper", "scissors")):
        options_str = "\n\t"   "\n\t".join(f'{x 1}. {opt}' for x,opt in enumerate(options))
        while True:
            userchoice = input(f"Type in your choice:{options_str}\n").lower()
            try:
                userchoice = int(userchoice)
                if 1 <= userchoice <= len(options):
                    return options[int(userchoice) - 1]
            except:
                if userchoice in options:
                    return userchoice
            print("Invalid Input.")

Note: this uses try/except but only for the string-to-int conversion. Also, the code will work if the user types the word instead of a number.
Sample run:

>>> RockPaperScissors.getUserChoice()
Type in your choice:
    1. rock
    2. paper
    3. scissors
4
Invalid Input.
Type in your choice:
    1. rock
    2. paper
    3. scissors
3
'scissors'

Typing the word:

>>> RockPaperScissors.getUserChoice()
Type in your choice:
    1. rock
    2. paper
    3. scissors
Paper
'paper'

And, it works with any options:

>>> RockPaperScissors.getUserChoice(("C", "C  ", "Python", "Java", "Prolog"))
Type in your choice:
    1. C
    2. C  
    3. Python
    4. Java
    5. Prolog
3
'Python'

CodePudding user response:

Try this. I hope this helps you out. Best of luck!

class RockPaperScissors:
    def getUserChoice(self):
        while True:
            try:
                userchoice = input("Type in your choice: rock, paper, scissors: ")
                if userchoice not in ("rock", "paper", "scissors"):   
                    raise ValueError
            except ValueError:
                print("Invalid Input!\nTry typing in your choice again")   
                continue
            else:
                print("You choice is:", userchoice)
            return userchoice.lower()
  • Related