开发者

Help creating exam grading program in Python

开发者 https://www.devze.com 2023-02-24 17:10 出处:网络
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 开发者_Python百科when I

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 开发者_Python百科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 answer to the last line of the answerKey.

for line in answerKey:
    answer = line.split()

The for line in studentExam: loop runs afterwards, but answer doesn't change in this loop and will stay the same.

The solution is combining the loops using zip:

for answerLine, studentLine in zip(answerKey, studentExam):
    answer = answerLine.split()
    studentAnswer = studentLine.split()

Also, remember to close the files when you're done with them:

answerKey.close()
studentExam.close()


Wouldn't the problem be that you iterate over all the lines in answerkey.txt and then end up comparing its last line only to all studentexam.txt lines?


You are overwriting your answer in every iteration of the for line loop. A is most likely the last entry in your answer key. Try combining the two for loops into just one!

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号