Python Forum
Random quiz generator
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Random quiz generator
#1
#! python3
# randomQuizGenerator.py - Creates quizzes with questions and answers in
# random order, along with the answer key.

import random

# The quiz data. Keys are states and values are their capitals.
capitals = {'Alabama': 'Montgomery', 'Alaska': 'Juneau', 'Arizona': 'Phoenix',
   'Arkansas': 'Little Rock', 'California': 'Sacramento', 'Colorado': 'Denver',
   'Connecticut': 'Hartford', 'Delaware': 'Dover', 'Florida': 'Tallahassee',
   'Georgia': 'Atlanta', 'Hawaii': 'Honolulu', 'Idaho': 'Boise', 'Illinois':
   'Springfield', 'Indiana': 'Indianapolis', 'Iowa': 'Des Moines', 'Kansas':
   'Topeka', 'Kentucky': 'Frankfort', 'Louisiana': 'Baton Rouge', 'Maine':
   'Augusta', 'Maryland': 'Annapolis', 'Massachusetts': 'Boston', 'Michigan':
   'Lansing', 'Minnesota': 'Saint Paul', 'Mississippi': 'Jackson', 'Missouri':
   'Jefferson City', 'Montana': 'Helena', 'Nebraska': 'Lincoln', 'Nevada':
   'Carson City', 'New Hampshire': 'Concord', 'New Jersey': 'Trenton', 'New Mexico': 'Santa Fe', 'New York': 'Albany', 'North Carolina': 'Raleigh',
   'North Dakota': 'Bismarck', 'Ohio': 'Columbus', 'Oklahoma': 'Oklahoma City',
   'Oregon': 'Salem', 'Pennsylvania': 'Harrisburg', 'Rhode Island': 'Providence',
   'South Carolina': 'Columbia', 'South Dakota': 'Pierre', 'Tennessee':
   'Nashville', 'Texas': 'Austin', 'Utah': 'Salt Lake City', 'Vermont':
   'Montpelier', 'Virginia': 'Richmond', 'Washington': 'Olympia', 'West Virginia': 'Charleston', 'Wisconsin': 'Madison', 'Wyoming': 'Cheyenne'}

# Generate 35 quiz files
for quizNum in range(35):
    # Create the quizz and answer key files
    quizFile = open('capitalsquiz%s.txt' % (quizNum + 1), 'w')
    answerKeyFile = open('capitalsquiz_answers%s.txt' % (quizNum + 1), 'w')
	
	# Write out the header for the quiz.
    quizFile.write('Name:\n\nDate:\n\nPeriod:\n\n')
    quizFile.write((' ' * 20) + 'State Capitals Quiz (Forms %s)' % (quizNum + 1))
    quizFile.write('\n\n')
	
	# Shuffle the order of the states.
    states = list(capitals.keys())
    random.shuffle(states)
	
	# 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 + list(correctAnswer)
        random.shuffle(answerOptions)
		
	    # Write the question and the answer options to the quiz file.
        quizFile.write('{}{What is the capital of %s?\n'}'.format('questionNum+1', states[questionNum]))
        for i in range(4):
            quizFile.write('{}{}'.format('ABCD'[i], answerOptions[i]))
            quizFile.write('\n')
	    # Write the answer key to a file.
        answerKeyFile.write('{}{}\n'.format(questionNum + 1, 'ABCD'[answerOptions.index(correctAnswer)]))
        quizFile.close()
        answerKeyFile.close()
			
I know that this program must have several errors but let's start with the first one:
Error:
C:\Python36\kodovi>randomquizgenerator.py File "C:\Python36\kodovi\randomQuizGenerator.py", line 50 quizFile.write('{}{What is the capital of %s?\n'}'.format('questionNum+1', st ates[questionNum])) ^ SyntaxError: invalid syntax
In line 50 I'm not sure how to add name of state to the question by using .format().
It should look smth like "What is the capital of Alabama?".
Reply
#2
quizFile.write('{}What is the capital of %s?\n{}'.format('questionNum+1', states[questionNum]))
The place holder was wrong. I don't know if you want it there.
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply
#3
Thank you. Don't really know, I will when the program works out :)

Now, as I expected, an another error appears
Error:
Traceback (most recent call last): File "C:\Python36\kodovi\randomQuizGenerator.py", line 55, in <module> answerKeyFile.write('{}{}\n'.format(questionNum + 1, 'ABCD'[answerOptions.in dex(correctAnswer)])) ValueError: 'Helena' is not in list
Each time I run it there is a different city in the message.
Reply
#4
The code is really hard to follow.
I don't know why are you doing it but on line 46 you turn the capital ('correctAnswer') into a list. Print 'answerOptions' to see for sure what exactly is happening. However, this could be:
45 answerOptions = random.sample( wrongAnswers ,3)
46 answerOptions.append(correctAnswer)
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply
#5
I had to turn correctAnswer into list because wrongAnswers is already a list and we can't add string to list in line 46.

after rewriting lines 45 and 46 as you suggested it looks that this problem is solved but there is an another one.
Error:
Traceback (most recent call last): File "C:\Python36\kodovi\proba.py", line 50, in <module> quizFile.write('{}What is the capital of %s\n{}'.format('questionNum+1', sta tes[questionNum])) ValueError: I/O operation on closed file.
Reply
#6
Lines 56 and 57 - closing the files. Do you read the error? It says "ValueError: I/O operation on closed file."

The two lines are inside the for loop code block. In the first iteration, the files are closed and cause the error. Unindent the lines one step.
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply
#7
Thank you.

Since that running this file doesn't give any output I assume that I should add some print statements, just need to figure out where.

edit: files are created in my folder but unfortunately line 50 doesn't work as I was hoping for so questions within quiz files don't look good, it's very messy.
Reply
#8
What is in line 50?
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply
#9
quizFile.write('{}What is the capital of %s\n{}'.format('questionNum+1', states[questionNum]))
Reply
#10
quizFile.write('{:>2} What is the capital of {}\n'.format(questionNum+1, states[questionNum]))
Maybe that way?
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Random Generator: From Word to Numbers, from Numbers to n possibles Words Yamiyozx 2 1,421 Jan-02-2023, 05:08 PM
Last Post: deanhystad
  Random Sentance Generator Liquid_Ocelot 1 3,990 May-19-2017, 10:59 PM
Last Post: ichabod801

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020