KeyErrors and how to raise KeyError

For my homework, I am asked to raise a key error if the key (text) that the user enters contains any non-alphabetic characters and reprompt. So far I have it 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") 
+6
source share
1 answer

This is not an appropriate use of KeyError (it should be used to search in a speaker or similar situations), but if this is what you were asked to do, 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 
+11
source

Source: https://habr.com/ru/post/901413/


All Articles