I am trying to create a program that reads multiple choice answers from a txt file and compares them to a set answer key. This is what I have so far but the problem is that that when I run it, the answer key gets stuck on a single letter throughout the life of the program. I have put a print statement right after the for answerKey line and it prints out correctly, but when it compares the “exam” answers to the answer key it gets stuck and always thinks “A” should be the correct answer. Which is weird because it is the 3rd entry in my sample answer key.
Here’s the code:
answerKey = open("answerkey.txt" , 'r')
studentExam = open("studentexam.txt" , 'r')
index = 0
numCorrect = 0
for line in answerKey:
answer = line.split()
for line in studentExam:
studentAnswer = line.split()
if studentAnswer != answer:
print("You got question number", index + 1, "wrong\nThe correct answer was" ,answer , "but you answered", studentAnswer)
index += 1
else:
numCorrect += 1
index += 1
grade = int((numCorrect / 20) * 100)
print("The number of correctly answered questions:" , numCorrect)
print("The number of incorrectly answered questions:" , 20 - numCorrect)
print("Your grade is" ,grade ,"%")
if grade <= 75:
print("You have not passed")
else:
print("Congrats! You passed!")
Thanks for any help you can give me!
The problem is that you’re not nesting the loops properly.
This loop runs first, and ends up setting
answerto the last line of the answerKey.The
for line in studentExam:loop runs afterwards, butanswerdoesn’t change in this loop and will stay the same.The solution is combining the loops using
zip:Also, remember to close the files when you’re done with them: