python 根据词典问题和答案创建几个测验(随机排序)。

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python 根据词典问题和答案创建几个测验(随机排序)。相关的知识,希望对你有一定的参考价值。

#! python2
# randomQuizGenerator.py - Creates quizzes with questions and answer in
# random order, along with the answer key

import random

#The number of quizes to generate (aka how many students)
quizzQty = 15

#The quiz data; keys are questions and values are answers
quizQuestions = {'What is the Periodic element Li': 'Lithium',
                 'What is the Periodic element Na': 'Sodium',
                 'What is the Periodic element K': 'Potassium',
                 'What is the Periodic element Rb': 'Rubidium',
                 'What is the Periodic element Cs': 'Caesium',
                 'What is the Periodic element Fr': 'Francium',}
bonusQuestion = 'What types of Metals are these?'
bonusAnswer = "Alkali Metals"

#Generate a quiz question for each question.
for quizNum in range(quizzQty):
    #Create the quiz and answer key files.
    quizFile = open('quiz%s.txt' % (quizNum + 1), 'w')
    answerKeyFile = open('quiz_answers%s.txt' % (quizNum + 1), 'w')

    #Write out a header for the quiz
    quizFile.write('Name:\n\nDate:\n\nPeriod:\n\n')
    quizFile.write((' '*20) + 'Quiz (Form %s)' % (quizNum + 1))
    quizFile.write('\n\n')

    #Shuffle the order of the Questions
    questions = list(quizQuestions.keys())
    random.shuffle(questions)

    #Loop through all states, making a question for each
    for questionNum in range(len(quizQuestions)):
        #Get right and wrong answers
        correctAnswer = quizQuestions[questions[questionNum]]
        wrongAnswers = list(quizQuestions.values())
        del wrongAnswers[wrongAnswers.index(correctAnswer)]
        wrongAnswers = random.sample(wrongAnswers, 3)
        answerOptions = wrongAnswers + [correctAnswer]
        random.shuffle(answerOptions)

        #Write the question and the answer options to the quiz file.
        quizFile.write('%s. %s?\n' % (questionNum + 1, questions[questionNum]))
        for i in range(4):
            quizFile.write('\t%s. %s\n' % ('ABCD'[i], answerOptions[i]))

        quizFile.write('\n')

        #Write the answer key to a file
        answerKeyFile.write('%s. %s\n' % (questionNum + 1,
                                          'ABCD'[answerOptions.index(correctAnswer)]))

    #Write out a bonus question
    quizFile.write('Bonus Question:\n%s?' % (bonusQuestion))
    answerKeyFile.write('Bonus Answer:\n%s' % (bonusAnswer))

    #Close out the files
    quizFile.close()
    answerKeyFile.close()

以上是关于python 根据词典问题和答案创建几个测验(随机排序)。的主要内容,如果未能解决你的问题,请参考以下文章

Python实践练习:生成随机的测验试卷文件

python实践项目八:生成随机试卷文件

Python(3.6.4) - 创建随机测验

python 在指定的文件夹下生成随机的测验试卷文件

创建测验并从外部文件中召唤问题和答案

如何使用 PHP、MySQL 和 Jquery 创建测验