b1nary0mega
5/10/2017 - 1:43 PM

Create several quizzes (randomly ordered) based on a dictionaries questions and answers.

Create several quizzes (randomly ordered) based on a dictionaries questions and answers.

#! 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()