Python Calculator Source Code
Below is the complete Python source code for a feature-rich calculator application that demonstrates fundamental programming concepts while providing practical mathematical functionality.
import math
def add(x, y):
return x + y
def subtract(x, y):
return x - y
def multiply(x, y):
return x * y
def divide(x, y):
if y == 0:
return "Error! Division by zero."
return x / y
def power(x, y):
return x ** y
def square_root(x):
if x < 0:
return "Error! Cannot calculate square root of negative number."
return math.sqrt(x)
def percentage(x):
return x / 100
# Memory functions
memory = 0
def memory_store(value):
global memory
memory = value
def memory_recall():
return memory
def memory_clear():
global memory
memory = 0
def memory_add(value):
global memory
memory += value
def memory_subtract(value):
global memory
memory -= value
def calculator():
print("Advanced Python Calculator")
print("Operations: +, -, *, /, sqrt, ^, %, ms (memory store), mr (memory recall), mc (memory clear), m+ (memory add), m- (memory subtract)")
print("Type 'quit' to exit")
while True:
try:
# Get first number
num1_input = input("Enter first number or memory operation (mr, mc, m+, m-): ")
if num1_input.lower() == 'quit':
break
# Check for memory operations
if num1_input.lower() == 'mr':
print(f"Memory value: {memory_recall()}")
continue
elif num1_input.lower() == 'mc':
memory_clear()
print("Memory cleared")
continue
elif num1_input.lower() == 'm+':
value = float(input("Enter value to add to memory: "))
memory_add(value)
print(f"Memory updated: {memory_recall()}")
continue
elif num1_input.lower() == 'm-':
value = float(input("Enter value to subtract from memory: "))
memory_subtract(value)
print(f"Memory updated: {memory_recall()}")
continue
else:
num1 = float(num1_input)
# Get operation
operation = input("Enter operation (+, -, *, /, sqrt, ^, %): ")
if operation == 'sqrt':
result = square_root(num1)
print(f"√{num1} = {result}")
elif operation == '%':
result = percentage(num1)
print(f"{num1}% = {result}")
elif operation in ['+', '-', '*', '/']:
# Get second number for binary operations
num2 = float(input("Enter second number: "))
if operation == '+':
result = add(num1, num2)
elif operation == '-':
result = subtract(num1, num2)
elif operation == '*':
result = multiply(num1, num2)
elif operation == '/':
result = divide(num1, num2)
print(f"{num1} {operation} {num2} = {result}")
elif operation == '^':
# Get second number for power operation
num2 = float(input("Enter exponent: "))
result = power(num1, num2)
print(f"{num1} ^ {num2} = {result}")
else:
print("Invalid operation!")
# Ask if user wants to continue
choice = input("Do you want to perform another calculation? (y/n): ")
if choice.lower() != 'y':
break
except ValueError:
print("Invalid input! Please enter valid numbers.")
except Exception as e:
print(f"An error occurred: {e}")
if __name__ == "__main__":
calculator()
Features Included in This Implementation
- Basic Operations: Addition, subtraction, multiplication, division
- Advanced Functions: Square root calculation, exponentiation, percentage conversion
- Memory Management: Store values (ms), recall (mr), clear (mc), add to memory (m+), subtract from memory (m-)
- Error Handling: Division by zero, invalid inputs, negative square roots
- User Experience: Clear prompts, continuous operation loop, quit option
How to Run the Calculator
- Save the code in a file named
calculator.py - Open a terminal or command prompt
- Navigate to the directory containing the file
- Run the script using:
python calculator.py
Usage Examples
- Basic arithmetic: Enter 5, then +, then 3 → Result: 8
- Square root: Enter 16, then sqrt → Result: 4.0
- Exponentiation: Enter 2, then ^, then 3 → Result: 8.0
- Percentage: Enter 50, then % → Result: 0.5
- Memory operations:
- Enter 10, then m+ (add to memory)
- Enter mr (recall memory) → Result: 10.0
- Enter mc (clear memory)
This calculator serves as an excellent learning tool for understanding Python programming fundamentals including functions, user input handling, error management, and control flow structures.