对于我的家庭作业,我被告知如果用户输入的密钥(文本)包含任何非字母字符并重新提示,则会引发密钥错误.到目前为止,我有这个似乎工作,但显然不使用预期的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")
Run Code Online (Sandbox Code Playgroud)
wim*_*wim 14
这不适合使用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
Run Code Online (Sandbox Code Playgroud)