有没有办法使Python返回错误输入文本的错误



我正在创建一个程序,该程序内部将有一个或否选项。我想知道是否有一种方法可以使python返回"未经授权的文本",如果是的,则可以输入其他内容。

,您可以 raise Exception作为参数传递给它。

def f(my_input):
    if my_input in ("Yes", "No"):
        return "Success"
    else:
        raise Exception("Unauthorized text")
print f("Yes")
print f("No")
print f("StackOverflow")

输出:

Success
Success
Traceback (most recent call last):
  ...
Exception: Unauthorized text

编辑: @tripleee评论,如果不是您期望的话,您可以简单返回字符串:

def f(my_input):
    if my_input in ("Yes", "No"):
        return "Success"
    else:
        return "Unauthorized text"

如果您想继续询问直到它们正确为止:

def getYesNo(msg=None):
    if msg is None: msg = "Yes or No?"
    choice = ''
    choices = {'yes': True, 'y': True, 'no': False, 'n': False}
    while choice.lower() not in choices:
        choice = raw_input(msg + ' ')
    return choices[choice]

如果要提出异常:

def getYesNo(msg=None):
    if msg is None: msg = "Yes or No?"
    choice = ''
    choices = {'yes': True, 'y': True, 'no': False, 'n': False}
    choice = raw_input(msg + ' ')
    if choice not in choices:
        raise ValueError, "Unauthorized Text"
    return choices[choice]

也许是这样的东西?

if input.lower() == 'yes':
    # do one thing
elif input.lower() == 'no':
    # do another thing
else:
    print "unauthorized text"

最新更新