For my homework assignment, I am told to raise a key error if the key(text) the user enters contains any non alphabetic characters and reprompt. So far I have this which seems to work but obviously doesn't use the expected try/except structure
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")
Python KeyError is raised when we try to access a key from dict, which doesn't exist.
When working with dictionaries in Python, a KeyError gets raised when you try to access an item that doesn't exist in a Python dictionary. This is simple to fix when you're the one writing/testing the code – you can either check for spelling errors or use a key you know exists in the dictionary.
A Python KeyError exception is what is raised when you try to access a key that isn't in a dictionary ( dict ). Python's official documentation says that the KeyError is raised when a mapping key is accessed and isn't found in the mapping. A mapping is a data structure that maps one set of values to another.
Using try-except The try-except block is one of the best possible ways to handle the KeyError exceptions. It is also useful where the get() and the if and in operators are not supported. Here, in this example, there are two cases— normal case and a backup case.
This is not appropriate usage of KeyError
(it's supposed to be used for dict lookups, or similar situations), but if it is what you have been asked to do then try something like this :
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With