Skip to content

Commit 4f8fa3c

Browse files
TypeError for non-integer input (#9250)
* type error check * remove str input * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
1 parent 7b996e2 commit 4f8fa3c

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

maths/number_of_digits.py

+24
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,15 @@ def num_digits(n: int) -> int:
1616
1
1717
>>> num_digits(-123456)
1818
6
19+
>>> num_digits('123') # Raises a TypeError for non-integer input
20+
Traceback (most recent call last):
21+
...
22+
TypeError: Input must be an integer
1923
"""
24+
25+
if not isinstance(n, int):
26+
raise TypeError("Input must be an integer")
27+
2028
digits = 0
2129
n = abs(n)
2230
while True:
@@ -42,7 +50,15 @@ def num_digits_fast(n: int) -> int:
4250
1
4351
>>> num_digits_fast(-123456)
4452
6
53+
>>> num_digits('123') # Raises a TypeError for non-integer input
54+
Traceback (most recent call last):
55+
...
56+
TypeError: Input must be an integer
4557
"""
58+
59+
if not isinstance(n, int):
60+
raise TypeError("Input must be an integer")
61+
4662
return 1 if n == 0 else math.floor(math.log(abs(n), 10) + 1)
4763

4864

@@ -61,7 +77,15 @@ def num_digits_faster(n: int) -> int:
6177
1
6278
>>> num_digits_faster(-123456)
6379
6
80+
>>> num_digits('123') # Raises a TypeError for non-integer input
81+
Traceback (most recent call last):
82+
...
83+
TypeError: Input must be an integer
6484
"""
85+
86+
if not isinstance(n, int):
87+
raise TypeError("Input must be an integer")
88+
6589
return len(str(abs(n)))
6690

6791

0 commit comments

Comments
 (0)