【发布时间】:2011-04-12 08:56:39
【问题描述】:
我正在尝试创建一个程序,该程序从 txt 文件中读取多项选择答案并将它们与设置的答案键进行比较。这是我到目前为止所拥有的,但问题是当我运行它时,答案键在程序的整个生命周期中都会卡在一个字母上。我在 for answerKey 行之后放置了一个打印语句,它可以正确打印出来,但是当它将“考试”答案与答案键进行比较时,它会卡住并且总是认为“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!")
感谢您能给我的任何帮助!
【问题讨论】:
-
文本文件的格式是什么?
-
请提供示例输入文件以及使用这些输入文件运行程序时得到的输出。
-
您能否添加一些示例
answerkey.txt和studentexam.txtfile。我认为问题在于您正在比较两个数组(studentAnswer != answer)而不是它们的内容......