首页 > 解决方案 > 如何在 Python 中使用循环进行测验?

问题描述

我是 Python 新手,我试图创建一个测验,但我不知道如何制作这个程序。


测验是一个带有空格的短语,您需要在空格中输入正确的单词。如果单词是正确的,请在空白处打印带有正确单词的短语。如果错误,请打印重试。
我正在尝试这样的事情:

phrase = 'HTML is HyperText __1__ __2__.'
answers = ['Markup','Language']

def quiz(p,a):
    """ I can do it manually with if statements, 
        but this is not a good idea.""""

有人能帮我吗?

标签: pythonloopsautomation

解决方案


此方法按顺序迭代答案(根据您的评论)。

为了遍历每个答案,for 使用了一个循环。循环内部for是一个while循环,它会不断地询问用户输入,直到他们得到正确的答案,然后它会更新短语并跳出while循环。

blank = "_____"
phrase = ["HTML is HyperText ", blank, " ", blank]
answers = ['Markup','Language'] 
def quiz(phrase, answers):
    for answer in answers:
        while True:
            # "".join() converts the list into a string
            inp = raw_input("".join(phrase)+" ") #replace with input() in python3 
            if inp == answer:
                # Updates the first available blank with the answer
                phrase[phrase.index(blank)] = answer
                break

考虑添加一个.lower()函数以使输入不区分大小写。在 raw_input 上调用它并回答。

if inp.lower() == answer.lower():

推荐阅读