Robert Johns | 18 Feb, 2025
Fact checked by Jim Markus

Build a Simple Python Calculator (Step-by-Step Guide)

Want to enhance your Python skills by building a useful project? In this tutorial, we’ll create a Python calculator that performs essential arithmetic operations, exponentiation, and includes memory recall/clearing functionality.

This beginner-friendly project introduces important programming concepts such as:

  • Handling user input and validation
  • Using functions for modular programming
  • Implementing loops and conditional statements
  • Storing and managing a simple memory feature

By the end, you’ll have a fully functional calculator that you can use in your terminal. Let’s get started!

Step 1: Setting Up the Project

Before we start coding, let’s set up our Python project:

1. Make sure Python is installed on your computer. If not, download it from the official Python website.
2. Open your favorite code editor or IDE.
3. Create a new Python file, for example, calculator.py.

Great, now, let's dive head first into our Python editor to get this build started.

Step 2: Understanding How the Calculator Works

Our command line calculator will perform the following tasks:

  • Prompt the user to select an operation: addition, subtraction, multiplication, division, or exponentiation.
  • Ask the user to input two numbers.
  • Perform the selected operation and display the result.
  • Allow the user to store a result in memory and recall or clear it.
  • Continue running until the user decides to exit.

Step 3: Writing the Calculator Functions

Now, let’s define the functions that handle each arithmetic operation.

# Basic Arithmetic Functions
def add(a, b):
    return a + b

def subtract(a, b):
    return a - b

def multiply(a, b):
    return a * b

def divide(a, b):
    return a / b if b != 0 else 'Error: Division by zero'

def exponentiate(a, b):
    return a ** b

How It Works:

  • Each function takes two numbers and performs the corresponding operation.

  • The divide() function checks for division by zero and prevents errors.

  • This modular approach makes our calculator easy to expand and maintain.

Breaking It Down Further:

Using Functions for Clean Code

Each operation is wrapped in a function, making the code modular and reusable.

Handling Division by Zero Gracefully

def divide(a, b):
    return a / b if b != 0 else 'Error: Division by zero'
  • If b is zero, the function returns an error message instead of causing a crash.

Keeping the Code Readable with Clear Naming

Function names like add(), subtract(), and multiply() make the code self-explanatory, improving readability and maintainability.

Now that we have our core functions ready, let’s move on to memory storage.

Step 4: Implementing Memory Functions

We’ll include a simple memory system that lets users store and recall the last result.

# Memory Storage
memory = None

def store_memory(value):
    global memory
    memory = value
    print("Stored in memory.")

def recall_memory():
    return memory if memory is not None else "No value in memory."

def clear_memory():
    global memory
    memory = None
    print("Memory cleared.")

How It Works:

  • store_memory() saves the last result in memory.

  • recall_memory() retrieves the stored value or notifies if memory is empty.

  • clear_memory() erases stored values.

  • This allows users to work with previous results without needing to re-enter numbers.

Why Do We Use a Global Variable?

The memory variable is defined outside any function, making it global so that multiple functions can access and modify it. This allows:

  • Consistent data storage: The stored value remains available across different function calls.

  • Ease of use: Users can store, recall, and clear memory seamlessly.

  • Global scope necessity: Without using global, each function would treat memory as a local variable, meaning changes wouldn’t persist between function calls.

By using global memory, we ensure that the stored value is maintained across different user interactions.

Now that we have memory management in place, let’s proceed to handle user input and execute calculations.

Step 5: User Input and Running the Calculator

Now, let’s build the main while loop that manages user input, executes calculations, and interacts with memory storage.

# Main Calculator Loop
def calculator():
    while True:
        print("\nSimple Calculator")
        print("Select operation:")
        print("1. Addition (+)")
        print("2. Subtraction (-)")
        print("3. Multiplication (*)")
        print("4. Division (/)")
        print("5. Exponentiation (^)")
        print("6. Recall Memory (M)")
        print("7. Clear Memory (MC)")
        print("8. Exit (X)")
        
        choice = input("Enter choice: ").strip().lower()
        
        if choice in ['x', '8']:
            print("Exiting calculator. Goodbye!")
            break
        elif choice in ['m', '6']:
            print("Memory: ", recall_memory())
            continue
        elif choice in ['mc', '7']:
            clear_memory()
            continue
        
        if choice not in ['1', '2', '3', '4', '5', '+', '-', '*', '/', '^']:
            print("Invalid input. Try again.")
            continue
        
        try:
            num1 = float(input("Enter first number: "))
            num2 = float(input("Enter second number: "))
        except ValueError:
            print("Invalid number. Please enter numeric values.")
            continue
        
        if choice in ['1', '+']:
            result = add(num1, num2)
        elif choice in ['2', '-']:
            result = subtract(num1, num2)
        elif choice in ['3', '*']:
            result = multiply(num1, num2)
        elif choice in ['4', '/']:
            result = divide(num1, num2)
        elif choice in ['5', '^']:
            result = exponentiate(num1, num2)
        
        print("Result: ", result)
        
        store_option = input("Store result in memory? (y/n): ").strip().lower()
        if store_option == 'y':
            store_memory(result)

How It Works:

  • The user selects an operation.
  • Numbers are taken as input and converted to floats.
  • A function is called based on user selection.
  • The result is displayed and can be stored in memory.
  • The loop continues until the user exits.

Breaking It Down Further:

Continuous Execution with a While Loop

The loop ensures that the calculator runs continuously until the user decides to exit.

Input Handling and Validation

  • Users are prompted to enter a valid choice.

  • Numeric values are validated to prevent errors.

Memory Interaction

  • Users can recall (M) or clear (MC) stored values at any time.

  • The calculator allows saving results for reuse.

By structuring our main loop this way, we create a user-friendly experience while maintaining robust error handling.

Step 6: Running the Calculator

To make sure our program runs correctly, we use:

if __name__ == '__main__':
    calculator()

Why Is This Needed?

  • Direct Execution: Ensures the script runs only when executed directly, not when imported as a module.

  • Best Practices: Following this pattern allows for future code expansion while maintaining clarity.

  • Encapsulation: Keeps the calculator function separate from execution logic, improving code organization.

By adding this simple if __name__ == '__main__': check, we make our code more scalable and reusable in larger projects.

Final Code: Calculator

# Basic Arithmetic Functions
def add(a, b):
    return a + b

def subtract(a, b):
    return a - b

def multiply(a, b):
    return a * b

def divide(a, b):
    return a / b if b != 0 else 'Error: Division by zero'

def exponentiate(a, b):
    return a ** b

# Memory Storage
memory = None

def store_memory(value):
    """Stores the last calculated result in memory."""
    global memory
    memory = value
    print("Stored in memory.")

def recall_memory():
    """Retrieves the last stored value from memory."""
    return memory if memory is not None else "No value in memory."

def clear_memory():
    """Clears the stored value in memory."""
    global memory
    memory = None
    print("Memory cleared.")

# Main Calculator Loop
def calculator():
    while True:
        print("\nSimple Calculator")
        print("Select operation:")
        print("1. Addition (+)")
        print("2. Subtraction (-)")
        print("3. Multiplication (*)")
        print("4. Division (/)")
        print("5. Exponentiation (^)")
        print("6. Recall Memory (M)")
        print("7. Clear Memory (MC)")
        print("8. Exit (X)")

        choice = input("Enter choice: ").strip().lower()

        if choice in ['x', '8']:
            print("Exiting calculator. Goodbye!")
            break
        elif choice in ['m', '6']:
            print("Memory: ", recall_memory())
            continue
        elif choice in ['mc', '7']:
            clear_memory()
            continue

        if choice not in ['1', '2', '3', '4', '5', '+', '-', '*', '/', '^']:
            print("Invalid input. Try again.")
            continue

        try:
            num1 = float(input("Enter first number: "))
            num2 = float(input("Enter second number: "))
        except ValueError:
            print("Invalid number. Please enter numeric values.")
            continue

        if choice in ['1', '+']:
            result = add(num1, num2)
        elif choice in ['2', '-']:
            result = subtract(num1, num2)
        elif choice in ['3', '*']:
            result = multiply(num1, num2)
        elif choice in ['4', '/']:
            result = divide(num1, num2)
        elif choice in ['5', '^']:
            result = exponentiate(num1, num2)

        print("Result: ", result)

        store_option = input("Store result in memory? (y/n): ").strip().lower()
        if store_option == 'y':
            store_memory(result)

# Ensures the script runs correctly when executed directly
if __name__ == '__main__':
    calculator()

Wrapping Up

Congratulations! You’ve built a fully functional command line calculator in Python.

This project helped you learn:

- User input handling and validation
- Functions for modular programming
- Loops for continuous execution
- Conditional statements for decision-making
- Implementing a simple memory storage system

Next Steps: Enhance Your Calculator!

  • Add support for square root and logarithms.
  • Implement a history feature to keep track of previous calculations.
  • Create a graphical user interface (GUI) using Tkinter or PyQt.

The best way to learn Python is by building fun projects — so keep experimenting!

By Robert Johns

Technical Editor for Hackr.io | 15+ Years in Python, Java, SQL, C++, C#, JavaScript, Ruby, PHP, .NET, MATLAB, HTML & CSS, and more... 10+ Years in Networking, Cloud, APIs, Linux | 5+ Years in Data Science | 2x PhDs in Structural & Blast Engineering

View all post by the author

Subscribe to our Newsletter for Articles, News, & Jobs.

I accept the Terms and Conditions.

Disclosure: Hackr.io is supported by its audience. When you purchase through links on our site, we may earn an affiliate commission.

In this article

Learn More

Please login to leave comments