简体   繁体   English

如果用户在 python 中输入了无效的字符串选项,我应该如何处理异常?

[英]If a user enters an invalid string option in python how should I handle the exception?

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 ie "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()

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:如果您想在每次尝试失败后提醒用户输入选择,使用像None这样的标记值非常有帮助:

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:您还可以在 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

In this case, you probably do not need an exception.在这种情况下,您可能不需要异常。
You probably want to loop again on input().你可能想在 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.当你想在上层处理错误时,try|except 机制更合适。

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.注意:这使用try/except但仅用于字符串到整数的转换。 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'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM