leo_someone
leo_someone

Reputation: 75

Creating a multiple choice quiz python

I'm trying to write a program to create a file that will contain a multiple choice quiz for people to print or do whatever they want with it. I know how to do the file writing, but am stuck on how to make the choices for the question. The question would ask for the capital of the state, and the choices would give 4 possibilities, with only one being correct. Here is the code:

import random

state_capitals = A DICTIONARY of the states and their capitals which I spared you because it was really big :D


file = open(r'''C:\Users\Leo\Desktop\Quiz1CSL.txt''',"w")
#The range(1) is just there as a place holder for later
for x in range(1):

    file.write("Austin's Computer Science State Capitals Quiz\n")

    for x in range(10):
        random_state = random.choice(list(state_capitals.keys()))
        main_typed = "What is the capital of"
        question_mark = "?"
        file.write("\n")
        file.write('{0} {1}{2}\n'.format(main_typed, random_state,question_mark))

file.close()

Upvotes: 2

Views: 3610

Answers (1)

Patrick Artner
Patrick Artner

Reputation: 51653

I removed your file-write code, have a look at the marked lines for how to get a sample of 3 + one correct answer from your dict:

import random

# testdata "Capitals" as states, "lowercase" as capital ;)
state_capitals = dict([(chr(b).upper(),chr(b)) for b in range(ord("a"),ord("z")+1)])

for x in range(10):
    random_state = random.choice(list(state_capitals.keys()))
    main_typed = "What is the capital of"
    question_mark = "?"

    choices = sorted( random.sample([state_capitals[x] for x in state_capitals if x != random_state],3) + [state_capitals[random_state]])
    # random.samples(list,n) gives you n unique random values from list
    # and I add in the "correct" one, by sorting them you have a uniform
    # a to z order that lets the correct one vanish into the others.

    print('{0} {1}{2}'.format(main_typed, random_state,question_mark))
    print('Choices: ' + ",".join(choices))

With Michael Butchers excellent suggestion this boils down to:

for x in range(10):
    choices = random.sample(list(state_capitals),4) 
    random_state = random.choice(choices)
    main_typed = "What is the capital of"
    question_mark = "?"

    print('{0} {1}{2}'.format(main_typed, random_state,question_mark))
    print('Choices: ' + ",".join([state_capitals[x] for x in choices]))

Output:

What is the capital of F?
Choices: f,i,p,r
What is the capital of P?
Choices: h,j,p,w
What is the capital of J?
Choices: g,i,j,v
What is the capital of B?
Choices: b,n,s,w
What is the capital of C?
Choices: c,p,s,z
What is the capital of U?
Choices: g,l,u,w
What is the capital of C?
Choices: c,g,h,t
What is the capital of B?
Choices: b,o,y,z
What is the capital of R?
Choices: e,k,r,w
What is the capital of P?
Choices: b,p,x,z

Upvotes: 1

Related Questions