Math Quiz Game in Python

Python game 19 of 20

Beginner⏱ 20 min📄 38 lines of Python★ 3 challenges▶ Plays in your browser

Math Sprint throws ten random sums at you (adding, taking away and times tables) and times how fast you answer. It's a great small project because it uses random numbers, a loop, a dictionary of operators and the time module, and you can make it as easy or as hard as you like.

Pick a level, then go as fast as you can. Wrong answers show the right one so you can learn.

Play Math Sprint

math_quiz_game.py · real Python in your browser
Press ▶ Play to start the game. When it asks you something, type your answer and press Enter.
View and edit the code (38 lines)

How to play

  • Choose level 1 (small numbers) or 2 (bigger numbers).
  • Type the answer to each sum and press Enter.
  • Your score and time appear at the end.

The complete Math Sprint code

Here is the whole program (38 lines). It only uses Python's standard library, so it runs anywhere Python 3 is installed.

import operator
import random
import time

OPS = {"+": operator.add, "-": operator.sub, "x": operator.mul}


def make_question(level):
    sign = random.choice(list(OPS))
    top = 10 if level == 1 else 20
    a, b = random.randint(1, top), random.randint(1, top)
    if sign == "-" and b > a:
        a, b = b, a                      # no negative answers
    if sign == "x":
        b = random.randint(2, 9 if level == 1 else 12)
    return a, sign, b, OPS[sign](a, b)


print("MATH SPRINT  -  10 sums, as fast as you can")
level = input("Level 1 or 2? ").strip()
level = 2 if level == "2" else 1
score = 0
start = time.time()

for n in range(1, 11):
    a, sign, b, answer = make_question(level)
    reply = input(f"Q{n}: {a} {sign} {b} = ").strip()
    if reply.lstrip("-").isdigit() and int(reply) == answer:
        score += 1
        print("  ✓")
    else:
        print(f"  ✗  It's {answer}")

seconds = time.time() - start
print(f"\nScore: {score}/10 in {seconds:.1f} seconds")
print(f"That's {seconds / 10:.1f} seconds per question.")
if score == 10 and seconds < 40:
    print("Lightning fast and perfect!")

How the Math Sprint game works, step by step

01Keep operators in a dictionary

The operator module has functions for +, - and *. Mapping the symbol to the function means OPS["x"](6, 7) works out 42.

OPS = {"+": operator.add, "-": operator.sub, "x": operator.mul}

02Make a fair question

Pick a sign and two numbers. For take-away, swap the numbers if needed so the answer isn't negative; for times, keep the second number small like a times table.

if sign == "-" and b > a:
    a, b = b, a

03Time the sprint

time.time() is the number of seconds since 1970. Read it before and after, and the difference is how long you took.

start = time.time()
...
seconds = time.time() - start

04Check answers without crashing

.isdigit() guards int() so typing a letter just counts as wrong. :.1f rounds the time to one decimal place.

if reply.lstrip("-").isdigit() and int(reply) == answer:

What you'll learn

  • The operator module
  • Functions stored in a dictionary
  • Timing with time.time()
  • Tuple unpacking from a function
  • Number formatting in f-strings

Python concepts in this game:

Math Sprint coding challenges

Write the key parts of the game yourself. Press Run to try your code and Check to test it. Each challenge you pass earns a star (saved in this browser).

1/3

Work out a sum

Write calc(a, sign, b) where sign is "+", "-" or "x". Return the answer.

challenge 1 · edit, Run, then Check
Hint

One if for each sign. Python's times sign is *.

Show a solution
def calc(a, sign, b):
    if sign == "+":
        return a + b
    if sign == "-":
        return a - b
    return a * b

print(calc(6, "x", 7))
2/3

Mark the reply

Write mark(reply, answer): reply is what the player typed (text). Return True only if it's a whole number (maybe with a minus sign and spaces) equal to answer. Never crash.

challenge 2 · edit, Run, then Check
Hint

Strip spaces, check reply.lstrip("-").isdigit(), then compare int(reply).

Show a solution
def mark(reply, answer):
    reply = reply.strip()
    if not reply.lstrip("-").isdigit():
        return False
    return int(reply) == answer

print(mark(" 42 ", 42))
3/3

Times table round

Read the table number with input(), then print its first 5 lines exactly like 7 x 1 = 7 up to 7 x 5 = 35.

challenge 3 · edit, Run, then Check
Hint

for i in range(1, 6): then print(f"{n} x {i} = {n * i}").

Show a solution
n = int(input("Which table? "))
for i in range(1, 6):
    print(f"{n} x {i} = {n * i}")

Make it your own

Once your challenges pass, try one of these upgrades:

  • Add division with whole-number answers.
  • Make the game harder after every correct answer.
  • Keep a best time for each level.
  • Give bonus points for answers under 3 seconds.

Frequently asked questions

How do you make a math quiz in Python?

Generate two random numbers and an operator, ask the question with input(), compare the reply with the real answer, and repeat in a loop while counting the score.

How do I time a quiz in Python?

Save time.time() before the first question and subtract it from time.time() after the last one. The result is the number of seconds taken.

Is this good for practising times tables?

Yes. Change OPS to only {'x': operator.mul} and every question becomes a times-table question.

More games like this