我有以下代码将列表转换为多项选择测验:
def practise_test(test):
score = 0
for question in test:
while True:
print(question[question])
reaction = input (question[options] + '\n')
if reaction == question[answer]:
print ('\nright answered!')
print('The answer is indeed {}. {}\n'.format(question[answer], question[explanation]))
score += 1
break
else:
print ('\nIncorrect answer.')
print ('The correct answer is {}. {}\n'.format(question[answer], question[explanation]))
break
print (score)
但是现在我必须向practise_test
函数中添加一些代码,以便在您键入:'previous'时转到上一个问题。有人有解决此问题的想法吗?
答案 0 :(得分:0)
您可以将for循环与while循环交换,并在用户写“ previous”的情况下更改索引i。顺便说一句。您正在使用的双循环对我来说似乎不必要。
example_test = [
{"question": "1 + 1", "answer": "2", "explanation": "math", "options": "2, 4, 6, 8"},
{"question": "2 + 2", "answer": "4", "explanation": "math", "options": "2, 4, 6, 8"},
{"question": "3 + 3", "answer": "6", "explanation": "math", "options": "2, 4, 6, 8"},
{"question": "4 + 4", "answer": "8", "explanation": "math", "options": "2, 4, 6, 8"},
]
def practise_test(test):
score = 0
i = 0
while i < len(test):
question = test[i]
print(question["question"])
reaction = input(question["options"] + '\n')
if reaction == question["answer"]:
print ('\nright answered!')
print('The answer is indeed {}. {}\n'.format(question["answer"], question["explanation"]))
score += 1
elif reaction.startswith("previous"):
i -= 2
i = max(i, -1)
else:
print ('\nIncorrect answer.')
print ('The correct answer is {}. {}\n'.format(question["answer"], question["explanation"]))
i += 1
print (score)
practise_test(example_test)
似乎也缺少使用字典键作为字符串,但这就像我不知道其余实现一样的猜测。