KeyError及如何引发KeyError

10 投票
1 回答
41604 浏览
提问于 2025-04-17 06:16

在我的作业中,我被要求如果用户输入的键(文本)包含任何非字母字符,就要抛出一个键错误,并重新提示用户。到目前为止,我写的代码似乎能正常工作,但显然没有使用预期的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 个回答

21

这其实不是正确使用KeyError的方式(它通常是用来处理字典查找或者类似的情况),不过如果这是你被要求做的事情,那你可以试试下面这样的写法:

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

撰写回答