How to generate multiple choice questions with Python

python to multiple choices

This is a script to make you do fast multiple choice questions

from random import shuffle

alt1 = """red, rosso
yellow, giallo
green, verde
white, bianco"""

alt1 = alt1.splitlines()
qnum = len(alt1)

sol = alt1.copy()
questions = []
answers = []
for q in alt1:
	q, a = q.split(",")
	questions.append(q)
	answers.append(a)

qna = []
lettsol = []
letters = "abcd"
for n in range(qnum):
	a1 = sol[n].split(",")[1]
	pos = answers.index(a1)
	answers.pop(pos)
	a2, a3, a4 = answers
	qq = f"What is the italian word for {questions[n]}"
	x = [a1, a2, a3, a4]
	shuffle(x)
	right = x.index(a1)
	lettsol.append(letters[right])
	qna.append([qq, x])
	answers.insert(pos, a1)
# print(*qna, sep="\n")
counter = 0

for q in qna:
	q, a = q
	print(q)
	for ans in a:
		print(f"{letters[counter]})" + ans)
		counter += 1
	counter = 0
	print()


print("\nSolutions")
counter = 0
for ss in sol:
	q, s = ss.split(",")
	print(q, s, " [" + lettsol[counter] + "]")
	counter += 1

This is the output

What is the italian word for red
a) verde
b) bianco
c) giallo
d) rosso

What is the italian word for yellow
a) giallo
b) rosso
c) verde
d) bianco

What is the italian word for green
a) bianco
b) rosso
c) verde
d) giallo

What is the italian word for white
a) bianco
b) rosso
c) verde
d) giallo


Solutions
red  rosso  [d]
yellow  giallo  [a]
green  verde  [c]
white  bianco  [a]
>>> 

Putting more than 4 questions but having always 4 multiple choices

from random import shuffle, sample

alt1 = """red, rosso
yellow, giallo
green, verde
white, bianco
black, nero
orange, arancione"""

alt1 = alt1.splitlines()
qnum = len(alt1)

sol = alt1.copy()
questions = []
answers = []
for q in alt1:
	q, a = q.split(",")
	questions.append(q)
	answers.append(a)

qna = []
lettsol = []
letters = "abcd"
for n in range(qnum):
	a1 = sol[n].split(",")[1]
	pos = answers.index(a1)
	answers.pop(pos)
	shuffle(answers)
	a2, a3, a4 = sample(answers, 3)
	qq = f"What is the italian word for {questions[n]}"
	x = [a1, a2, a3, a4]
	shuffle(x)
	right = x.index(a1)
	lettsol.append(letters[right])
	qna.append([qq, x])
	answers.insert(pos, a1)
# print(*qna, sep="\n")
counter = 0

for q in qna:
	q, a = q
	print(q)
	for ans in a:
		print(f"{letters[counter]})" + ans)
		counter += 1
	counter = 0
	print()


print("\nSolutions")
counter = 0
for ss in sol:
	q, s = ss.split(",")
	print(q, s, " [" + lettsol[counter] + "]")
	counter += 1

output


Subscribe to the newsletter for updates
Tkinter templates
Avatar My youtube channel

Twitter: @pythonprogrammi - python_pygame

Videos

Speech recognition game

Pygame's Platform Game

Other Pygame's posts

Published by pythonprogramming

Started with basic on the spectrum, loved javascript in the 90ies and python in the 2000, now I am back with python, still making some javascript stuff when needed.