如何在测验中添加next和previous[python]

2024-06-02 12:40:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下代码可以将列表转换为多项选择测验:

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'时,就可以转到前面的问题。有人有办法解决这个问题吗


Tags: the代码answertestformat列表isdef
1条回答
网友
1楼 · 发布于 2024-06-02 12:40:49

您可以将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)

似乎还缺少的是使用字典键作为字符串,但这只是猜测,因为我不知道其余的实现

相关问题 更多 >