Skip to content

Commit 19ccc52

Browse files
committed
Add division.py with input validation for zero denominator
- Create maths/division.py with divide_numbers() function - Add explicit validation for zero denominator - Include comprehensive docstring with examples - Add doctests for various cases including error handling - Follow repository coding standards with type hints Fixes #13845
1 parent ae68a78 commit 19ccc52

File tree

1 file changed

+68
-0
lines changed

1 file changed

+68
-0
lines changed

maths/division.py

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
"""
2+
This module provides a division function with input validation.
3+
4+
The divide_numbers function performs division between two numbers
5+
with explicit validation for zero denominators, providing clearer
6+
error messages for educational purposes.
7+
"""
8+
9+
10+
def divide_numbers(a: float, b: float) -> float:
11+
"""
12+
Divide two numbers with validation for zero denominator.
13+
14+
This function performs division between two numbers and includes
15+
explicit validation to prevent division by zero, providing a
16+
user-friendly error message that is especially helpful for
17+
beginners learning about error handling.
18+
19+
Args:
20+
a: The dividend (numerator) - the number to be divided.
21+
b: The divisor (denominator) - the number to divide by.
22+
23+
Returns:
24+
The result of dividing a by b.
25+
26+
Raises:
27+
ValueError: If b (denominator) is zero.
28+
29+
Examples:
30+
>>> divide_numbers(10, 2)
31+
5.0
32+
33+
>>> divide_numbers(15, 3)
34+
5.0
35+
36+
>>> divide_numbers(-10, 2)
37+
-5.0
38+
39+
>>> divide_numbers(7, 2)
40+
3.5
41+
42+
>>> divide_numbers(10, 0)
43+
Traceback (most recent call last):
44+
...
45+
ValueError: Cannot divide by zero. Please provide a non-zero denominator.
46+
47+
>>> divide_numbers(0, 5)
48+
0.0
49+
"""
50+
if b == 0:
51+
raise ValueError("Cannot divide by zero. Please provide a non-zero denominator.")
52+
return a / b
53+
54+
55+
if __name__ == "__main__":
56+
# Example usage
57+
print("Division Examples:")
58+
print(f"10 / 2 = {divide_numbers(10, 2)}")
59+
print(f"15 / 3 = {divide_numbers(15, 3)}")
60+
print(f"-10 / 2 = {divide_numbers(-10, 2)}")
61+
print(f"7 / 2 = {divide_numbers(7, 2)}")
62+
print(f"0 / 5 = {divide_numbers(0, 5)}")
63+
64+
# Test zero division error
65+
try:
66+
divide_numbers(10, 0)
67+
except ValueError as e:
68+
print(f"Error caught: {e}")

0 commit comments

Comments
 (0)