8章练习
#coding:utf-8
import random
capitals={'广东':'广州','福建':'福州','浙江':'杭州','江苏':'南京','山东':'济南','河北':'石家庄','河南':'郑州'}
tmpList=list(capitals)
title='''
Name:
Date:
Period:
'''
for i in range(7):
seq = 'State Capitals Quiz (Form %s)'.center(50, '*')%(i+1)
random.shuffle(tmpList) #共七分试卷,调整不同试卷问题的顺序
name='test'+ str(i) +'.txt' #生成试卷名称序号
answerName='test'+ str(i) +'_answer.txt' #生成试卷名称序号
with open(name,'a',encoding='utf-8')as testfile:
with open(answerName, 'a', encoding='utf-8')as anserfile:
testfile.write(title)
testfile.write(seq+'\n\n')
anserfile.write(seq+'\n\n')
for item in tmpList:
question=item+'的省会是:\n' #生成问题
testfile.write(question) # 写入题目
correctchoice=capitals[item] #生成正确选项
tmpValueList = list(capitals.values())#生成选项列表
tmpValueList.remove(correctchoice) #去除正确答案
tmpNum=random.sample(tmpValueList,3) #随机生成三个错误选项
tmpNum.append(correctchoice) #添加正确答案
random.shuffle(tmpNum) #打乱顺序
# testfile.write('A.'+tmpNum[0]+'\n'+'B.'+tmpNum[1]+'\n'+'C.'+tmpNum[2]+'\n'+'D.'+tmpNum[3]+'\n')#写入所有选项
for i in range(4):
testfile.write('ABCD'[i]+tmpNum[i]+'\n')
testfile.write('\n')
anserfile.write(question)
# if correctchoice==tmpNum[0]:
# anserfile.write('A.'+correctchoice+'\n')
# if correctchoice==tmpNum[1]:
# anserfile.write('B.'+correctchoice+'\n')
# if correctchoice==tmpNum[2]:
# anserfile.write('C.'+correctchoice+'\n')
# if correctchoice==tmpNum[3]:
# anserfile.write('D.'+correctchoice+'\n')
anserfile.write('ABCD'[tmpNum.index(correctchoice)]+'.'+correctchoice+'\n')