我正在尝试计算包含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
然后程序给出
答案:(用户可以在其中输入内容)
我试图用字典将问题的答案按出现的顺序排列,但我不确定那是有效的。任何建议,不胜感激!
答案 0 :(得分: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