Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

KeyErrors and how to raise a KeyError

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")
like image 657
user979616 Avatar asked Nov 14 '11 03:11

user979616


People also ask

When should I raise my KeyError?

Python KeyError is raised when we try to access a key from dict, which doesn't exist.

How do I fix KeyError in Python?

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.

What is KeyError A in Python?

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.

How do you handle key errors?

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.


1 Answers

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
like image 154
wim Avatar answered Oct 16 '22 13:10

wim