22-第2步_创建测验文件,并打乱问题的次序
第2步:创建测验文件,并打乱问题的次序
现在是时候填入那些 TODO
了。
循环中的代码将重复执行35次(每次生成一份测验试卷),因此在循环中,你只需要考虑生成一份测验试卷。首先你要创建一个实际的测验试卷文件,它需要有唯一的文件名,并且有某种标准的标题部分,还要留出位置,让学生填写姓名、日期和班级。然后需要得到随机排列的州的列表,稍后将用它来创建测验试卷的问题和答案。
在randomQuizGenerator.py中添加以下代码行:
#! python3
# randomQuizGenerator.py - Creates quizzes with questions and answers in
# random order, along with the answer key.
--snip--
# Generate 35 quiz files.
for quizNum in range(35):
# Create the quiz and answer key files.
❶ quizFile = open(f'capitalsquiz{quizNum + 1}.txt', 'w')
❷ answerKeyFile = open(f'capitalsquiz_answers{quizNum + 1}.txt', 'w')
# Write out the header for the quiz.
❸ quizFile.write('Name:\n\nDate:\n\nPeriod:\n\n')
quizFile.write((' ' * 20) + f'State Capitals Quiz (Form{quizNum + 1})')
quizFile.write('\n\n')
# Shuffle the order of the states.
states = list(capitals.keys())
❹ random.shuffle(states)
# TODO: Loop through all 50 states, making a question for each.
测验试卷的文件名将是capitalsquizquizNum
,即 for
循环的计数器。capitalsquiz'capitalsquiz%s.txt'
和 'capitalsquiz_answers%s.txt'
中的占位符 %s
都将被 (quizNum + 1)
取代,所以第一份测验试卷和答案将是capitalsquiz1.txt和capitalsquiz_answers1.txt。❶和❷的 open()
函数将创建这些文件,以 'w'
作为第二个参数,以写模式打开它们。
❸处的 write()
语句创建了测验标题,让学生填写。最后,利用 random. shuffle()
函数❹来创建美国州名的随机列表。该函数重新随机排列传递给它的列表中的值。