41 lines
1.0 KiB
Python
41 lines
1.0 KiB
Python
def _check_div_zero(b: float | int, op: str) -> None:
|
|
if op in ("/", "//") and b == 0:
|
|
raise ZeroDivisionError("division by zero")
|
|
|
|
|
|
def calculate(a: float | int, op: str, b: float | int) -> float:
|
|
"""Perform arithmetic operations with proper error handling.
|
|
|
|
Args:
|
|
a: First operand
|
|
op: Operation (+, -, *, /, **, //)
|
|
b: Second operand
|
|
|
|
Returns:
|
|
Result of the operation
|
|
|
|
Raises:
|
|
TypeError: If op is not a string
|
|
ValueError: If operation is unknown
|
|
ZeroDivisionError: If dividing by zero
|
|
"""
|
|
if not isinstance(op, str):
|
|
raise TypeError(f"operation must be a string, got {type(op).__name__}")
|
|
|
|
_check_div_zero(b, op)
|
|
|
|
match op:
|
|
case "+":
|
|
return a + b
|
|
case "-":
|
|
return a - b
|
|
case "*":
|
|
return a * b
|
|
case "/":
|
|
return a / b
|
|
case "**":
|
|
return a ** b
|
|
case "//":
|
|
return a // b
|
|
case _:
|
|
raise ValueError(f"unknown operation: {op!r}") |