Day 4 · Day 4: Functions & Modules
Modular Calculator
Build a calculator program organized into separate functions for each arithmetic operation, with proper error handling for invalid input and division by zero.
Requirements
1. Write separate functions: add, subtract, multiply, divide.
2. Each function takes two numbers and returns the result.
3. The divide function must handle division by zero gracefully (return an error message, not crash).
4. Build a menu loop that asks the user to choose an operation and enter two numbers.
5. Validate that user input is numeric using try/except.
6. Allow the user to perform multiple calculations until they choose to exit.
2. Each function takes two numbers and returns the result.
3. The divide function must handle division by zero gracefully (return an error message, not crash).
4. Build a menu loop that asks the user to choose an operation and enter two numbers.
5. Validate that user input is numeric using try/except.
6. Allow the user to perform multiple calculations until they choose to exit.
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: Cannot divide by zero"
return a / b
def get_number(prompt):
while True:
try:
return float(input(prompt))
except ValueError:
print("Invalid input. Please enter a number.")
def main():
operations = {
"1": ("Add", add),
"2": ("Subtract", subtract),
"3": ("Multiply", multiply),
"4": ("Divide", divide),
}
while True:
print("\n--- Modular Calculator ---")
for key, (name, _) in operations.items():
print(f"{key}. {name}")
print("5. Exit")
choice = input("Choose an operation: ")
if choice == "5":
print("Goodbye!")
break
if choice not in operations:
print("Invalid option.")
continue
name, func = operations[choice]
a = get_number("Enter first number: ")
b = get_number("Enter second number: ")
result = func(a, b)
print(f"Result: {result}")
if __name__ == "__main__":
main()
50 XP on completion
Back to Day 4
Your Code
Output
Click "Run" to execute your code...
⏳ Loading Python runtime (first run may take a few seconds)...
Log in to mark this project complete and earn XP.