Python Calculator Application
Table of Contents
In the last lesson, Python To-Do Application, we built a task manager that saves its data. Now we will build a command-line calculator with calculation history.
In this tutorial, we will build a Python calculator application from scratch using VS Code. This is a beginner-friendly project that teaches functions, loops, conditionals, and file handling. By the end, we will have a working calculator that can add, subtract, multiply, divide, and keep a history of calculations.
What Is a Calculator Application?
A calculator application is a program that helps us do math. We can add, subtract, multiply, and divide numbers. We type in two numbers and an operation, and the program gives us the result.
Think of it like the calculator app on your phone. But instead of tapping buttons, we type commands. And it runs in the terminal.
Calculators are one of the most common beginner projects. They teach us how to take input, make decisions, and show output. They also help us practice functions, loops, and error handling.
Features of Our Python Calculator
Our calculator will have these features:
- Add, subtract, multiply, divide
- Handle division by zero
- Keep a history of calculations
- Save history to a file
- Show history
Project Folder Structure
We will create a folder for our project. Inside it, we will have one Python file and one text file.
calculator_app/ calculator.py history.txtThe history.txt file stores our calculation history. It will be created automatically when we save our first calculation.
Let us set up the project in VS Code.
Setting Up the Project in VS Code
Step 1: Open VS Code
If we do not have VS Code installed, we can download it from code.visualstudio.com. It is free.
Once installed, open VS Code.
Step 2: Create a New Folder
- Click on File in the top menu.
- Click Open Folder.
- Navigate to where we want to keep our project (like Desktop or Documents).
- Click New Folder.
- Name it
calculator_app. - Click Select Folder.
Now VS Code is open with our new empty folder.
Step 3: Create the Python File
- In the left sidebar, we see our folder name
calculator_app. - Right-click on the folder name.
- Click New File.
- Name it
calculator.py. - Press Enter.
Now we have an empty calculator.py file ready for code.
Step 4: Open the Integrated Terminal
- Click on Terminal in the top menu.
- Click New Terminal.
A terminal panel opens at the bottom. It is already inside our calculator_app folder. So we do not need to cd anywhere.
Now we are ready to write code.
How to Create the Calculator in Python (Step by Step)
We will write the code in small steps. Before each step, we will explain what we are doing and why. We will mention which file we are editing (always calculator.py in this project).
Step 1: Import Required Modules
We need the os module to check if the history file exists.
import osStep 2: Define the History File
We will store calculation history in a file called history.txt. Let us define it as a constant.
HISTORY_FILE = "history.txt"Step 3: Create a Function to Save History
We need a function to save a calculation to the history file. We open the file in append mode and write the expression and result.
def save_history(expression, result): with open(HISTORY_FILE, "a") as file: file.write(f"{expression} = {result}\n")Step 4: Create a Function to Show History
Now let us write a function to show the history. We read the file and print its contents. If the file does not exist, we show a message.
def show_history(): try: with open(HISTORY_FILE, "r") as file: content = file.read() if content: print("\nCalculation History:") print("-" * 30) print(content.strip()) print("-" * 30) else: print("No history yet") except FileNotFoundError: print("No history yet")Step 5: Create Calculation Functions
Now let us write functions for each operation. Each function takes two numbers and returns the result.
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): if b == 0: return "Error: Division by zero" return a / bStep 6: Create a Function to Get User Numbers
Let us write a function to get two numbers from the user. We use float() so the user can enter decimals. If the input is not a number, we return None, None.
def get_numbers(): try: a = float(input("Enter first number: ")) b = float(input("Enter second number: ")) return a, b except ValueError: print("Please enter valid numbers") return None, NoneStep 7: Create the Main Menu Function
Now let us write the main function with a menu. It shows options and calls the right function based on the user’s choice.
def main(): while True: print("\n===== CALCULATOR =====") print("1. Add") print("2. Subtract") print("3. Multiply") print("4. Divide") print("5. Show history") print("6. Exit") choice = input("Enter your choice: ").strip()
if choice == "1": a, b = get_numbers() if a is not None: result = add(a, b) print(f"Result: {result}") save_history(f"{a} + {b}", result) elif choice == "2": a, b = get_numbers() if a is not None: result = subtract(a, b) print(f"Result: {result}") save_history(f"{a} - {b}", result) elif choice == "3": a, b = get_numbers() if a is not None: result = multiply(a, b) print(f"Result: {result}") save_history(f"{a} * {b}", result) elif choice == "4": a, b = get_numbers() if a is not None: result = divide(a, b) print(f"Result: {result}") save_history(f"{a} / {b}", result) elif choice == "5": show_history() elif choice == "6": print("Goodbye!") break else: print("Invalid choice")Step 8: Run the Calculator Program
Finally, let us add the program entry point.
if __name__ == "__main__": main()Complete Python Calculator Code
Now our complete calculator.py file looks like this.
import os
HISTORY_FILE = "history.txt"
def save_history(expression, result): with open(HISTORY_FILE, "a") as file: file.write(f"{expression} = {result}\n")
def show_history(): try: with open(HISTORY_FILE, "r") as file: content = file.read() if content: print("\nCalculation History:") print("-" * 30) print(content.strip()) print("-" * 30) else: print("No history yet") except FileNotFoundError: print("No history yet")
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): if b == 0: return "Error: Division by zero" return a / b
def get_numbers(): try: a = float(input("Enter first number: ")) b = float(input("Enter second number: ")) return a, b except ValueError: print("Please enter valid numbers") return None, None
def main(): while True: print("\n===== CALCULATOR =====") print("1. Add") print("2. Subtract") print("3. Multiply") print("4. Divide") print("5. Show history") print("6. Exit") choice = input("Enter your choice: ").strip()
if choice == "1": a, b = get_numbers() if a is not None: result = add(a, b) print(f"Result: {result}") save_history(f"{a} + {b}", result) elif choice == "2": a, b = get_numbers() if a is not None: result = subtract(a, b) print(f"Result: {result}") save_history(f"{a} - {b}", result) elif choice == "3": a, b = get_numbers() if a is not None: result = multiply(a, b) print(f"Result: {result}") save_history(f"{a} * {b}", result) elif choice == "4": a, b = get_numbers() if a is not None: result = divide(a, b) print(f"Result: {result}") save_history(f"{a} / {b}", result) elif choice == "5": show_history() elif choice == "6": print("Goodbye!") break else: print("Invalid choice")
if __name__ == "__main__": main()How to Run the Calculator in VS Code
We have two ways to run the program.
Way 1: Using the Terminal
In the VS Code terminal, type:
python calculator.pyWay 2: Using the Run Button
- Open
calculator.pyin the editor. - Look at the top right corner. There is a small play button (triangle).
- Click it. VS Code will run the file in the terminal.
Both ways work. Use whichever we prefer.
Example Output
===== CALCULATOR =====1. Add2. Subtract3. Multiply4. Divide5. Show history6. ExitEnter your choice: 1Enter first number: 5Enter second number: 3Result: 8.0
===== CALCULATOR =====...Enter your choice: 5
Calculation History:------------------------------5.0 + 3.0 = 8.0------------------------------That is our calculator. It is simple but complete. And we built it entirely in VS Code.
Exercises for Practice
Try these exercises to improve the calculator.
- Add a power function that calculates
a ** b. - Add a square root function.
- Add a memory feature that stores a value and lets us reuse it.
- Add a clear history option that deletes the history file.
- Add a percentage calculation (like 10% of 500).
- Make the calculator handle more than two numbers at once.
- Add a menu option to export the history to a CSV file.
Now let us build the next project: the Expense Tracker. We will also use VS Code for that.
Next, we will build a Python Expense Tracker that stores and summarizes spending data.