键错误和如何提升键

2024-04-24 15:08:29 发布

您现在位置:Python中文网/ 问答频道 /正文

对于我的家庭作业,我被告知,如果用户输入的密钥(文本)包含任何非字母字符和重新提示,则会引发密钥错误。到目前为止,我已经有了这个似乎可以工作,但显然没有使用预期的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")

Tags: thetokey用户youinputuse密钥
1条回答
网友
1楼 · 发布于 2024-04-24 15:08:29

这不是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

相关问题 更多 >