flashcards.py

Created by matt-numworks

Created on January 27, 2026

1.31 KB

This script practices basic arithmetic until the user types “quit” to end their session.


from random import randint, choice

def generate_flashcard():
    # Supported operators
    ops = ['+', '-', '*', '/']
    op = choice(ops)

    # Generate numbers
    num1 = randint(1, 12)
    num2 = randint(1, 12)

    # Ensure clean division
    if op == '/':
        num1 = num1 * num2

    # Compute answer manually
    if op == '+':
        answer = num1 + num2
    elif op == '-':
        answer = num1 - num2
    elif op == '*':
        answer = num1 * num2
    else:
        answer = num1 / num2

    return num1, op, num2, answer


def play_game():
    score = 0
    total = 0

    print("--- Math Flashcards! \n(Type 'Q' to exit) ---")

    while True:
        num1, op, num2, answer = generate_flashcard()

        # Ask the question
        user_input = input(str(num1) + " " + op + " " + str(num2) + " = ")

        if user_input == "Q":
            break

        try:
            user_answer = float(user_input)
            if user_answer == answer:
                print("Correct!")
                score += 1
            else:
                print("Incorrect. The answer was " + str(answer))
        except:
            print("Invalid input, please enter a number.")

        total += 1
        print("--------------------")

    print("Game Over! Your score: " + str(score) + "/" + str(total))


play_game()

During your visit to our site, NumWorks needs to install "cookies" or use other technologies to collect data about you in order to:

With the exception of Cookies essential to the operation of the site, NumWorks leaves you the choice: you can accept Cookies for audience measurement by clicking on the "Accept and continue" button, or refuse these Cookies by clicking on the "Continue without accepting" button or by continuing your browsing. You can update your choice at any time by clicking on the link "Manage my cookies" at the bottom of the page. For more information, please consult our cookies policy.