Add operand type validation and widen calculate() return type to int | float
This commit is contained in:
+9
-3
@@ -3,7 +3,7 @@ def _check_div_zero(b: float | int, op: str) -> None:
|
|||||||
raise ZeroDivisionError("division by zero")
|
raise ZeroDivisionError("division by zero")
|
||||||
|
|
||||||
|
|
||||||
def calculate(a: float | int, op: str, b: float | int) -> float:
|
def calculate(a: float | int, op: str, b: float | int) -> int | float:
|
||||||
"""Perform arithmetic operations with proper error handling.
|
"""Perform arithmetic operations with proper error handling.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
@@ -15,13 +15,19 @@ def calculate(a: float | int, op: str, b: float | int) -> float:
|
|||||||
Result of the operation
|
Result of the operation
|
||||||
|
|
||||||
Raises:
|
Raises:
|
||||||
TypeError: If op is not a string
|
TypeError: If op is not a string, or if a or b is not a number
|
||||||
ValueError: If operation is unknown
|
ValueError: If operation is unknown
|
||||||
ZeroDivisionError: If dividing by zero
|
ZeroDivisionError: If dividing by zero
|
||||||
"""
|
"""
|
||||||
if not isinstance(op, str):
|
if not isinstance(op, str):
|
||||||
raise TypeError(f"operation must be a string, got {type(op).__name__}")
|
raise TypeError(f"operation must be a string, got {type(op).__name__}")
|
||||||
|
|
||||||
|
if not isinstance(a, (int, float)):
|
||||||
|
raise TypeError(f"operand a must be a number, got {type(a).__name__}")
|
||||||
|
|
||||||
|
if not isinstance(b, (int, float)):
|
||||||
|
raise TypeError(f"operand b must be a number, got {type(b).__name__}")
|
||||||
|
|
||||||
_check_div_zero(b, op)
|
_check_div_zero(b, op)
|
||||||
|
|
||||||
match op:
|
match op:
|
||||||
@@ -38,4 +44,4 @@ def calculate(a: float | int, op: str, b: float | int) -> float:
|
|||||||
case "//":
|
case "//":
|
||||||
return a // b
|
return a // b
|
||||||
case _:
|
case _:
|
||||||
raise ValueError(f"unknown operation: {op!r}")
|
raise ValueError(f"unknown operation: {op!r}")
|
||||||
|
|||||||
Reference in New Issue
Block a user