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.

Code:

def vocabtest():
    for r in words.values():
        count = 0
        while count < 3:
            print("What word does the following definition correspond with?")
            print(r)
            answer = raw_input("> ")
            if words[answer] == r: #Error
                print("Correct!")
                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.

Recommended Answers

All 4 Replies

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
                print("Correct!")
                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?

Thanks.

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
        ...
commented: Very helpful and follows through with posts. +1

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!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.