-2

I am writing a spanish quiz in python, and I am running into a problem when the user inputs an incorrect answer in the quiz.

import random

def create_dictionary(filename):
   dictionary = {} 

   file = open(filename)  
   for line in file:

       line = line.replace('\n','')

       split = line.split(':') 
       spanish_words = split[1].split(',')
       dictionary[split[0]] = spanish_words 

   file.close()
   return dictionary

def main():

   dictionary = create_dictionary('project13_data.txt')

   print (dictionary)

   questions = int(input("How many questions do you want to be quizzed on? "))
   final = questions
   wrong = []

   while questions > 0:

       def good_guess():
           if val == answer[0] or answer[1]: 
               print("Correct\n")
           else:
               print("Wrong\n")
               wrong.append(find)


    find = random.choice(list(dictionary.keys()))
    answer = dictionary[find][0:2]

       print(find)
       print(answer)

       print("What is" ,find, "in spanish? ")
       val = input("Answer: ")
       good_guess() 

       questions = questions - 1

   print("You got", len(wrong), "wrong out of", final)
   print(list(wrong))
main()

The error that i am getting is

File "C:\Python34\Project 13 take 2.py", line 33, in good_guess if val == answer[0] or answer[1]: IndexError: list index out of range

If the user inputs a correct answer, the code runs fine, but otherwise I get the error. I do not know why I am getting this error, what can I do to fix this?

Troy
  • 1

2 Answers2

0

I think that your immediate problem is that answer is not defined when you get to that line of code. Neither is find, a few lines below. Those variables are in an outer scope. You should pass them into the function as arguments.

You may have a problem with redefining the built-in names, split and file as local variables.

Why do you redefine the function good_guess every time thorough your while loop? I think this should be placed at the top of main, or perhaps before it -- if you've set up answer and find as parameters.

BTW, your use of answer[0] is legal in Python 2.7.

Prune
  • 76,765
  • 14
  • 60
  • 81
-1

Unrelated to your error, if val == answer[0] or answer[1]: doesn't work this way.

Python will evaluate val == answer[0] and will return True or False. Depending on what value it gets it will then evaluate bool(answer[1]) which will return False if it's an empty string, an empty list or 0, and True otherwise.

Instead, use if val == answer[0] or val == answer[1] or better:
if val in [answer[0], answer[1]]:.

DeepSpace
  • 78,697
  • 11
  • 109
  • 154