#!/usr/bin/env python3 """ Simple calculator with basic arithmetic operations. Handles division by zero and provides simple testing. """ def add(a: float, b: float) -> float: """Return the sum of a and b.""" return a + b def subtract(a: float, b: float) -> float: """Return a minus b.""" return a - b def multiply(a: float, b: float) -> float: """Return a multiplied by b.""" return a * b def divide(a: float, b: float) -> float: """ Return a divided by b. Raises: ZeroDivisionError: if b is 0 """ if b == 0: raise ZeroDivisionError("Cannot divide by zero") return a / b def test_calculator(): """Test all calculator functions.""" print("Testing calculator functions...") # Test addition result = add(5, 3) expected = 8 assert result == expected, f"Addition failed: {result} != {expected}" print(f"[OK] add(5, 3) = {result}") # Test subtraction result = subtract(10, 4) expected = 6 assert result == expected, f"Subtraction failed: {result} != {expected}" print(f"[OK] subtract(10, 4) = {result}") # Test multiplication result = multiply(7, 6) expected = 42 assert result == expected, f"Multiplication failed: {result} != {expected}" print(f"[OK] multiply(7, 6) = {result}") # Test division result = divide(15, 3) expected = 5 assert result == expected, f"Division failed: {result} != {expected}" print(f"[OK] divide(15, 3) = {result}") # Test division by zero try: divide(10, 0) print("[ERROR] Division by zero should have raised an error") return False except ZeroDivisionError as e: print(f"[OK] divide(10, 0) raised: {e}") # Test with floats result = add(2.5, 3.7) expected = 6.2 assert abs(result - expected) < 0.0001, f"Float addition failed: {result} != {expected}" print(f"[OK] add(2.5, 3.7) = {result}") print("\n[PASSED] All tests passed!") return True def main(): """Main function to demonstrate calculator usage.""" print("Calculator Demo") print("-" * 50) # Demonstrate basic operations a, b = 20, 5 print(f"a = {a}, b = {b}") print(f"a + b = {add(a, b)}") print(f"a - b = {subtract(a, b)}") print(f"a * b = {multiply(a, b)}") print(f"a / b = {divide(a, b)}") print("\n" + "-" * 50) # Show division by zero handling print("Testing division by zero protection:") try: result = divide(a, 0) except ZeroDivisionError as e: print(f"Caught expected error: {e}") if __name__ == "__main__": # Run tests first if test_calculator(): print("\n" + "=" * 50) main()