当前位置:嗨网首页>书籍在线阅读

23-第3步_创建答案选项

  
选择背景色: 黄橙 洋红 淡粉 水蓝 草绿 白色 选择字体: 宋体 黑体 微软雅黑 楷体 选择字体大小: 恢复默认

第3步:创建答案选项

现在需要为每个问题生成答案选项,这将是A到D的多项选择。你需要创建另一个 for 循环,该循环生成测验试卷的50个问题的内容。然后里面会嵌套第三个 for 循环,为每个问题生成多重选项。让你的代码看起来像这样:

#! python3
# randomQuizGenerator.py - Creates quizzes with questions and answers in
# random order, along with the answer key.
--snip--
    # Loop through all 50 states, making a question for each. 
    for questionNum in range(50):
         # Get right and wrong answers.
      ❶ correctAnswer = capitals[states[questionNum]]
      ❷ wrongAnswers = list(capitals.values())
      ❸ del wrongAnswers[wrongAnswers.index(correctAnswer)]
      ❹ wrongAnswers = random.sample(wrongAnswers, 3)
      ❺ answerOptions = wrongAnswers + [correctAnswer]
      ❻ random.shuffle(answerOptions)
         # TODO: Write the question and answer options to the quiz file.
         # TODO: Write the answer key to a file.

很容易得到正确的答案,它作为一个值保存在 capitals 字典中❶。这个循环将遍历打乱的 states 列表中的州(从 states[0]states[49] ),在 capitals 中找到每个州,将该州对应的首府保存在 correctAnswer 中。

设置错误答案列表需要使用一点技巧。你可以从 capitals 字典中复制所有的值❷,删除正确的答案❸,然后从该列表中选择3个随机的值❹。 random.sample() 函数使得这种选择很容易,它的第一个参数是你希望选择的列表,第二个参数是你希望选择的值的个数。完整的答案选项列表是这3个错误答案与正确答案的组合❺。最后,答案需要随机排列❻,这样正确的答案就不会总是设置为选项D。