【问题标题】:Help creating exam grading program in Python帮助在 Python 中创建考试评分程序
【发布时间】: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.txtstudentexam.txtfile。我认为问题在于您正在比较两个数组(studentAnswer != answer)而不是它们的内容......

标签: python list split line


【解决方案1】:

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

此循环首先运行,最后将answer 设置为 answerKey 的最后一行。

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()

【讨论】:

    【解决方案2】:

    问题不在于您遍历 answerkey.txt 中的所有行,然后仅将其最后一行与所有 studentexam.txt 行进行比较吗?

    【讨论】:

      【解决方案3】:

      您在 for 行循环的每次迭代中都覆盖了您的答案。 A 很可能是答案键中的最后一个条目。尝试将两个 for 循环合并为一个!

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-11-18
        • 2022-11-29
        • 2016-08-08
        相关资源
        最近更新 更多