Skip to content

Commit 8b5bac1

Browse files
authored
Add division.py with divide_numbers function and zero division validation (fixes #13845)
This module provides a function to perform division with error handling for zero denominator, making it user-friendly for beginners.
1 parent a051ab5 commit 8b5bac1

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

maths/division.py

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
"""
2+
Division Algorithm with input validation for zero denominator.
3+
4+
This module provides a function to perform division with proper
5+
error handling for edge cases, especially for beginners learning
6+
algorithms.
7+
"""
8+
9+
10+
def divide_numbers(a: int | float, b: int | float) -> float:
11+
"""
12+
Divide two numbers with validation for zero denominator.
13+
14+
This function performs division of 'a' by 'b' with explicit validation
15+
to raise a ValueError when attempting to divide by zero. This makes the
16+
function more user-friendly and helps beginners understand error handling.
17+
18+
Args:
19+
a: The dividend (numerator)
20+
b: The divisor (denominator)
21+
22+
Returns:
23+
float: The result of dividing a by b
24+
25+
Raises:
26+
ValueError: If b (denominator) is zero
27+
28+
Examples:
29+
>>> divide_numbers(10, 2)
30+
5.0
31+
>>> divide_numbers(7, 2)
32+
3.5
33+
>>> divide_numbers(5, 0)
34+
Traceback (most recent call last):
35+
...
36+
ValueError: Cannot divide by zero. Please provide a non-zero denominator.
37+
"""
38+
if b == 0:
39+
raise ValueError("Cannot divide by zero. Please provide a non-zero denominator.")
40+
return a / b

0 commit comments

Comments
 (0)