Here's a simple calculator with history functionality implemented in Python. This calculator allows users to perform basic arithmetic operations (+, -, *, /) and keeps a record of all previous calculations.
✅ Features:
- Basic operations: addition, subtraction, multiplication, division
- Stores calculation history
- Displays history on demand
🧮 Python Code:
# Calculator with History
history = []
def add(a, b):
result = a + b
history.append(f"{a} + {b} = {result}")
return result
def subtract(a, b):
result = a - b
history.append(f"{a} - {b} = {result}")
return result
def multiply(a, b):
result = a * b
history.append(f"{a} * {b} = {result}")
return result
def divide(a, b):
try:
result = a / b
history.append(f"{a} / {b} = {result}")
return result
except ZeroDivisionError:
print("Error: Cannot divide by zero.")
history.append(f"{a} / {b} = Error: Division by zero")
return None
def show_history():
if not history:
print("No history available.")
else:
print("\n--- Calculation History ---")
for entry in history:
print(entry)
def main():
while True:
print("\nSelect an operation:")
print("1. Add (+)")
print("2. Subtract (-)")
print("3. Multiply (*)")
print("4. Divide (/)")
print("5. Show History")
print("6. Exit")
choice = input("Enter your choice (1/2/3/4/5/6): ")
if choice == '6':
print("Exiting the calculator.")
break
if choice == '5':
show_history()
continue
try:
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
except ValueError:
print("Invalid input. Please enter numeric values.")
continue
if choice == '1':
print("Result:", add(num1, num2))
elif choice == '2':
print("Result:", subtract(num1, num2))
elif choice == '3':
print("Result:", multiply(num1, num2))
elif choice == '4':
result = divide(num1, num2)
if result is not None:
print("Result:", result)
else:
print("Invalid choice. Please select a valid option.")
if __name__ == "__main__":
main()
💡 How to Use:
- Run the script.
- Choose an operation from the menu.
- Enter two numbers when prompted.
- The result will be displayed and saved in history.
- Select "Show History" to view all previous calculations.
Would you like this implemented as a GUI app using Tkinter or as a web-based calculator using HTML/JavaScript?