refactor: improve calculator with type hints, match/case, and error handling
This commit is contained in:
+37
-10
@@ -1,14 +1,41 @@
|
|||||||
def calc(a, b, op):
|
def _check_div_zero(b: float | int, op: str) -> None:
|
||||||
if op == "+":
|
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
|
return a + b
|
||||||
elif op == "-":
|
case "-":
|
||||||
return a - b
|
return a - b
|
||||||
elif op == "*":
|
case "*":
|
||||||
return a * b
|
return a * b
|
||||||
elif op == "/":
|
case "/":
|
||||||
if b != 0:
|
|
||||||
return a / b
|
return a / b
|
||||||
else:
|
case "**":
|
||||||
return "error"
|
return a ** b
|
||||||
else:
|
case "//":
|
||||||
return "unknown op"
|
return a // b
|
||||||
|
case _:
|
||||||
|
raise ValueError(f"unknown operation: {op!r}")
|
||||||
Reference in New Issue
Block a user