questions = [{'question': 'What does OSI stand for?',
'correct': ['Open Systems Interconnect'],
'incorrect': ['Open Systematic Information',
'Organised Stairway Interweb',
'Open Safe Internet']},
{'question': "What is the fourth Layer of the OSI Model?",
'correct': ['Transport Layer'],
'incorrect': ['Teleport Layer',
'Telecommunications Layer',
'Topology Layer']},
...]
现在你可以给用户一个给定数量的随机选择的问题,每次:
^{pr2}$
然后问一个问题:
for q_num, question in enumerate(to_answer, 1):
print("Question {0}: {1}".format(q_num, question['question']))
while True:
user_answer = input().lower()
if user_answer not in answer_key:
print("Not a valid answer")
else:
break
最后检查他们是否正确并报告:
correct = question['correct']
if answer_key[user_answer] in correct:
print("Correct!")
else:
s = "Incorrect; the correct answer{0}:"
print(s.format(" was" if len(correct) == 1 else "s were"))
for answer in correct:
print(answer)
Question 1: What does OSI stand for?
a: Open Systematic Information
b: Open Safe Internet
c: Organised Stairway Interweb
d: Open Systems Interconnect
e
Not a valid answer
b
Incorrect; the correct answer was:
Open Systems Interconnect
您可以将所有问题保存在字典列表中:
现在你可以给用户一个给定数量的随机选择的问题,每次:
^{pr2}$然后问一个问题:
并以随机顺序呈现答案,将每个答案存储在
answer_key
中对应的键(a
,b
,c
等):接受用户的输入:
最后检查他们是否正确并报告:
这支持一个问题有多个正确答案的可能性,并且尽可能少地硬编码,这样整个事情都由
questions
配置。这样可以减少代码的重复,并使以后更容易发现错误。在示例输出(对于
number_of_questions = 1
和questions
,如上所示):你可以简单地从文件中提取信息
您可以将答案放入列表中,并在列表上调用^{} :
每次运行时,它可能会产生不同的输出,例如:
^{pr2}$相关问题 更多 >
编程相关推荐