Hello, if you have seen any of my other posts you will know I am working on a script to make a "vocabulary test". I currently having it functioning nearly perfectly, except I get an error if I enter the wrong word.


def vocabtest():
    for r in words.values():
        count = 0
        while count < 3:
            print("What word does the following definition correspond with?")
            answer = raw_input("> ")
            if words[answer] == r: #Error
                count = 100000
            elif words[answer] != r:
                if count < 2:
                    count = count + 1
                    print("That is incorrect. Try again.")
                elif count == 2:
                    count = count + 1
                    print("That is incorrect. The answer was",str(words[r]) + ".")
                    fail[r] = words[r]

If I enter the wrong word, I get a Key Error at line 8. Would anybody be able to help? Thanks in advance.

8 Years
Discussion Span
Last Post by SoulMazer

Your problem is called "input validation". Each time that you ask some input to the user, there is a high probability that the user enters unexpected input and your program must handle this (= validate input). Here you could use a test like this

answer = raw_input("> ")
            answer = answer.strip() # <--- remove leading and trailing white space
            if answer not in words:
                pass # <-- Put here what you want to do when answer is not in words
            elif words[answer] == r: #Error
                count = 100000

However, I don't know what you want to do if the user enters an answer which is not in the dictionary.


Thanks Gribouillis, that solved my immediate problem. However, yes I am still a beginner, but how would I access...or just print the correct answer?



If you want to access the correct answer, you should iterate over the dictionary items instead of the values

def vocabtest():
    for a, r in words.items(): # <-- the answer is a
Votes + Comments
Very helpful and follows through with posts.

Thank you again. I have all my problems fixed. Now, however, I have a new problem. If you would be able to still help I would greatly appreciate it.

Thanks again!

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.