【问题标题】:How to count score of multiple-choice questions from a text file如何从文本文件中计算多项选择题的分数
【发布时间】:2019-05-02 13:42:11
【问题描述】:

我正在尝试计算包含 5 个问题和 4 个可能答案的文本文件中正确和错误答案的数量。截至目前,我能够一次遍历每个问题,并且用户能够给出答案,但是我似乎无法弄清楚如何计算用户给出的答案是对还是错。

我知道如何在其他更简单的代码中使用累加器值,但是当问题来自文本文件时,我只是不知道如何格式化它。

math_file = open("math.txt", 'r')
question_prompts = math_file.readlines()
count = 0
correct_answers = {"c":[0], "b":[1], "a":[2], "a":[3], "d":[4]}
startline = 0
for num in range(5):
    for i in range(startline, startline + 5):
        print(question_prompts[i])
    answer = input('Answer: ')
    startline = startline + 5
    if answer == correct_answers:
        count += 1

此代码一次正确地打印出一个文本文件问题,例如,第一个问题是: 什么是 4 x 6?

(a) 4

(b) 12

(c) 24

(d) 240

然后程序给出

答案:(用户可以在哪里输入)

我尝试使用字典将问题的答案按它们出现的顺序排列,但我不确定这是否有效。任何建议都非常感谢!

【问题讨论】:

  • 你在哪里使用字典?无处

标签: python python-3.x


【解决方案1】:
  • 您尝试使用的字典应该是相反的,并且字典中的值不应该在列表中。
  • if answer == correct_answers 是错误的,因为"a" != {0:"c", 1:b, 2:"a", 3:"a", 4:"d"}

    math_file = open("math.txt", 'r')
    question_prompts = math_file.readlines()
    count = 0
    correct_answers = {0:"c", 1:"b", 2:"a", 3:"a", 4:"d"}  # the line to change
    startline = 0
    for num in range(5):
        for i in range(startline, startline + 5):
            print(question_prompts[i])
        answer = input('Answer: ')
        startline = startline + 5
        if answer == correct_answers[num]: # the line to change
            count += 1
    

【讨论】:

  • 一些上下文:一般来说,字典应该使用你拥有的值作为键(问题编号)和你想要的值作为值(答案)。另一行更改是因为您要将答案与相应问题的字典值进行比较。此外,由于字典键是数字,您可以只使用列表并通过索引访问它们。
  • 谢谢!!这真的很有帮助!
猜你喜欢
  • 2019-05-09
  • 1970-01-01
  • 1970-01-01
  • 2021-12-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-18
  • 1970-01-01
相关资源
最近更新 更多