Learn Python · lesson 36 of 60 · about 9 minutes
Project: Quiz Engine
A quiz before school: ask() checks each answer and returns whether it was right, and grade() turns the score into a message.
What you'll learn
- Store questions as data
- Split the quiz into functions
- Return and combine results
A quiz before school
Sam wants three quick questions every morning. The questions and answers live in a list of (question, answer) tuples. ask(question, answer) asks one, tidies the reply, says whether it was right and returns True or False; the loop counts the Trues; and grade(right, out_of) returns a message for the score. Each function does one job, so a fourth question is just one more tuple.
Data plus functions
The questions live in a list of dictionaries. Three small functions do the work:
ask(question)shows a question and returns True if the answer is rightrun_quiz(questions)asks them all and returns the scorereport(score, total)turns the score into a message
The quiz engine
QUESTIONS = [
{"q": "2 + 2 = ", "a": "4"},
{"q": "Capital of France? ", "a": "paris"},
{"q": "Python keyword for functions? ", "a": "def"},
]
def ask(question):
reply = input(question["q"]).strip().lower()
return reply == question["a"]
def run_quiz(questions):
score = 0
for q in questions:
if ask(q):
score += 1
return score
def report(score, total):
percent = round(score / total * 100)
return f"You scored {score}/{total} ({percent}%)"
print(report(run_quiz(QUESTIONS), len(QUESTIONS)))Output
2 + 2 = Capital of France? Python keyword for functions? You scored 2/3 (67%)Tip
Names in CAPITALS, like QUESTIONS, are a convention for values that never change. Python doesn't enforce it, but programmers read it as "constant".
Now try it yourself
This lesson is free in Codiqo, with 8 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.