python - 如何在 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.""""
有人能帮我吗?
解决方案
此方法按顺序迭代答案(根据您的评论)。
为了遍历每个答案,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():
推荐阅读
- kubernetes - 在 pourcent 中设置限制 CPU 水平 Pod 自动缩放
- javascript - 如何正确使用 while 循环来大写文本字段内容,直到找到一个空字段?
- c# - 哪种方法更好:使用 EventLogReader 查询或使用 EntryWrittenEventHandler 获得通知?
- angular - 无法在 Angular 6 服务中找到“地图”
- pytest - 具有来自另一个夹具的参数化的 pytest 夹具
- python - Keras BatchNorm 层在训练和推理期间给出奇怪的结果
- javascript - Chrome 不支持 getUserMedia
- perl - 需要将二进制值转换为数字
- android - 从链接到我的应用程序的电话簿中删除联系人
- javascript - npm 检查需要哪个包子包