Day 010 of the 100 Days of Python challenge builds a command-line calculator for addition, subtraction, multiplication, and division. It also lets the user chain operations together, using the result of one calculation as the starting point for the next.

The most interesting idea in this project is using a dictionary to map operator symbols directly to functions, which avoids a long chain of if/elif statements for choosing which calculation to run. It’s a pattern worth understanding well, since it scales cleanly as you add more operations.

This guide walks through the complete Day 010 source code, explains the operator-dictionary pattern and the chaining logic, and explains two error-handling fixes: division by zero and restarting without recursion.

Project Overview

Each arithmetic operation has its own function. A dictionary maps an operator symbol to the matching function:

operations = {
    "+": addition,
    "-": subtraction,
    "*": multiplication,
    "/": division
}

This lets the calculator choose and call an operation without a long chain of conditional statements. The get_number() function repeatedly asks for input until it can convert the response to a float. After calculating a result, the user can continue with that answer, start a new calculation, or quit.

Source Code

The Day 010 project is contained in day010/main.py in the 100daysofpython repository:

# ======================
# Project Name: Day 10 - The Calculator
# Section: Beginner Python Projects
# Description: Python lists, dictionaries, functions and outputs
# ======================

# Import ASCII logo from external file
from art import LOGO

# Display the calculator logo and welcome message
print(LOGO)
print("*******************************************")
print("Welcome to The Calculator!")
print("*******************************************")

# --- Basic arithmetic functions ---

def addition(n1, n2):
    """Returns the sum of two numbers."""
    return n1 + n2

def subtraction(n1, n2):
    """Returns the difference of two numbers."""
    return n1 - n2

def multiplication(n1, n2):
    """Returns the product of two numbers."""
    return n1 * n2

def division(n1, n2):
    """Returns the quotient of two numbers, or None when dividing by zero."""
    if n2 == 0:
        return None
    return n1 / n2

# Dictionary mapping operator symbols to their corresponding functions
operations = {
    "+": addition,
    "-": subtraction,
    "*": multiplication,
    "/": division
}

def get_number(prompt):
    """Keeps asking until the user enters a valid number."""
    while True:
        try:
            return float(input(prompt))
        except ValueError:
            print("Invalid input! Please enter a number.")

def calculator():
    """Main calculator loop. Allows the user to chain operations, start fresh, or quit."""

    # Get the initial number from the user
    num1 = get_number("What is the first number?: ")

    while True:
        # Display all available operators
        for symbol in operations:
            print(symbol)

        # Keep asking until a valid operator is chosen
        while True:
            operation_symbol = input("Pick an operation: ")
            if operation_symbol in operations:
                break
            print("Invalid operator! Please choose +, -, * or /")

        # Get the second number, with validation
        num2 = get_number("What is the next number?: ")

        # Look up and call the matching function from the operations dictionary
        answer = operations[operation_symbol](num1, num2)
        if answer is None:
            print("Error: cannot divide by zero. Try again.")
            continue
        print(f"{num1} {operation_symbol} {num2} = {answer}")

        # Ask the user if they want to continue with the current result, start over, or quit
        choice = input(
            f"Type 'y' to continue calculating with {answer}, 'n' to start a new calculation, "
            "or 'q' to quit: "
        ).lower()

        if choice == "y":
            # Use the current answer as the first number for the next operation
            num1 = answer
        elif choice == "q":
            print("Goodbye")
            break
        else:
            # Clear the screen and start a new calculation (no recursion)
            print("\n" * 20)
            num1 = get_number("What is the first number?: ")

# Entry point — start the calculator
calculator()

How the Program Works

Mapping Operators to Functions

operations = {
    "+": addition,
    "-": subtraction,
    "*": multiplication,
    "/": division
}

In Python, functions are values, just like numbers or strings — they can be stored in a dictionary, passed around, and called later. This dictionary maps each operator symbol directly to the function that implements it, so looking up and calling the right operation is a single line:

answer = operations[operation_symbol](num1, num2)

operations[operation_symbol] retrieves the matching function (say, addition), and the trailing (num1, num2) immediately calls it. Adding a new operator later — like % for modulo — only requires writing a new function and adding one entry to the dictionary, with no changes needed to the lookup logic itself.

Validating Numeric Input With a Reusable Function

def get_number(prompt):
    while True:
        try:
            return float(input(prompt))
        except ValueError:
            print("Invalid input! Please enter a number.")

Rather than duplicating the same validation loop for both the first and second number, get_number() is a small reusable function that keeps asking until it gets valid input, then returns the moment it succeeds — a clean way to avoid repeating the same try/except pattern twice.

Chaining, Restarting, or Quitting

choice = input(
    f"Type 'y' to continue calculating with {answer}, 'n' to start a new calculation, "
    "or 'q' to quit: "
).lower()

if choice == "y":
    # Use the current answer as the first number for the next operation
    num1 = answer
elif choice == "q":
    print("Goodbye")
    break
else:
    # Clear the screen and start a new calculation (no recursion)
    print("\n" * 20)
    num1 = get_number("What is the first number?: ")

After each result, the user has three options. With y, the previous answer becomes the new num1 and the loop continues, so 10 + 5 followed by * 2 works as two interactive steps. With q, break ends the while True loop and the program finishes. Anything else clears the screen by printing blank lines and asks for a fresh first number, still inside the same loop. .lower() means Y and Q work too.

Two Error-Handling Fixes

An earlier version of this calculator had two gaps. Both are fixed in the current code, and each shows a useful technique.

Handling Division by Zero

def division(n1, n2):
    """Returns the quotient of two numbers, or None when dividing by zero."""
    if n2 == 0:
        return None
    return n1 / n2
answer = operations[operation_symbol](num1, num2)
if answer is None:
    print("Error: cannot divide by zero. Try again.")
    continue

Originally, division() just returned n1 / n2, so dividing by 0 raised a ZeroDivisionError and crashed the program. Now division() returns None for a zero divisor, and the main loop checks for it, prints a friendly message, and uses continue to go back to choosing an operation with the same first number. Returning None as a “no result” signal is a common Python pattern; a try/except ZeroDivisionError would work too.

Restarting With a Loop Instead of Recursion

The earlier version started a new calculation by calling calculator() from inside itself, which is recursion. Each restart added another frame to Python’s call stack that wasn’t released until the whole session ended, so a long enough session could eventually hit Python’s recursion limit and crash with a RecursionError.

The current code wraps everything in one while True loop instead. Starting over just asks for a new first number and continues the same loop, and quitting uses break. The flag variable the old version used to stop the loop is gone too: while True plus break says the same thing more directly.

What This Project Teaches

Day 010 combines:

  • Functions as values, stored and looked up in a dictionary
  • Reusable input-validation functions
  • A while True loop with continue and break to control the program’s flow
  • Returning None to signal “no result,” and checking for it
  • Why a loop is usually a better way to restart a program than recursion

The project is intentionally simple and does not implement mathematical precedence: each operation is performed in the order the user selects it, so 10 + 5 * 2 entered as two separate steps calculates (10 + 5) * 2, not 10 + (5 * 2).

Running the Project

git clone https://github.com/victorhugo81/100daysofpython.git
cd 100daysofpython/day010
python main.py

Possible Next Steps

Once you understand the code, try extending it:

  • Add more operators, like exponentiation (**) or modulo (%), to see how little code the dictionary pattern requires for each new one
  • Track and display a history of every calculation performed in the session
  • Round long decimal results, like 10 / 3, to a set number of places before printing them
  • Accept a whole expression like 12 * 3 on one line and split it into its parts

Conclusion

Day 010 of the 100 Days of Python challenge shows how mapping operators to functions in a dictionary keeps a calculator’s logic clean and easy to extend, while a single while True loop handles chaining, restarting, and quitting. Its two fixes, returning None for division by zero and replacing recursion with a loop, are small changes that turn a program that can crash into one that can’t.

View the Day 010 source code on GitHub, then continue through the repository’s project index as you build more Python programs, one day and one small project at a time.

Want to keep learning? These related guides pair well with this post: