KeyErrors以及如何引发KeyError

时间:2011-11-14 03:32:39

标签: python exception

对于我的家庭作业,我被告知如果用户输入的密钥(文本)包含任何非字母字符并重新提示,则会引发密钥错误。到目前为止,我有这个似乎工作,但显然不使用预期的try / except结构

key=input("Please enter the key word you want to use: ")
ok=key.isalpha()
while (ok==False):
    print("The key you entered is invalid. Please try again")
    key=input("Please enter the key word you want to use")

1 个答案:

答案 0 :(得分:13)

这是 KeyError的适当用法(它应该用于dict查找或类似的情况),但是如果它是你被要求做的那么尝试一下像这样:

def prompt_thing():
    s = raw_input("Please enter the key word you want to use: ")
    if s == '' or not s.isalnum():
        print("The key you entered is invalid. Please try again")
        raise KeyError('non-alphanumeric character in input')
    return s

s = None
while s is None:
    try:
        s = prompt_thing()
    except KeyError:
        pass