帮忙创建Python考试评分程序

0 投票
3 回答
3078 浏览
提问于 2025-04-16 15:33

我正在尝试创建一个程序,这个程序可以从一个txt文件中读取多项选择的答案,并将这些答案与一个标准答案进行比较。到目前为止,我写的代码是这样的,但问题是,当我运行这个程序时,标准答案在程序运行期间一直停留在一个字母上。我在for answerKey那一行后面加了一个打印语句,它打印的结果是正确的,但当程序将“考试”答案与标准答案进行比较时,它总是认为“A”是正确答案。这很奇怪,因为在我的示例答案中,“A”是第三个条目。

这是我的代码:

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!")

谢谢你能给我的任何帮助!

3 个回答

0

你在每次循环的时候都在覆盖你的答案。A 很可能是你答案中的最后一个条目。试着把这两个循环合并成一个吧!

2

问题是不是在于你遍历了answerkey.txt里的所有行,然后最后只把它的最后一行和studentexam.txt里的所有行进行比较呢?

3

问题在于你的循环没有正确嵌套。

这个循环先执行,结果把 answer 设置成了答案键的最后一行。

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

接下来的 for line in studentExam: 循环虽然运行了,但在这个循环中 answer 并没有改变,还是保持原来的值。

解决办法是使用 zip 来合并这两个循环:

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

另外,记得在完成操作后关闭文件:

answerKey.close()
studentExam.close()

撰写回答