Skip to content

Commit 075a379

Browse files
committed
Enhanced factorial function with proper error handling
1 parent b16e235 commit 075a379

File tree

1 file changed

+12
-18
lines changed

1 file changed

+12
-18
lines changed

factorial.py

+12-18
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,13 @@
1-
#!/usr/bin/env python3
2-
#function computes factorial of a given number
31
def factorial(n):
4-
result = 1
5-
i=1
6-
while i<=n:
7-
result*=i
8-
i+=1
9-
return result
10-
def test_answer():
11-
assert factorial(4) == 24
12-
13-
#read input from user
14-
n = 5 #int(input('Enter a number: '))
15-
16-
#calculate factorial
17-
result = factorial(n)
18-
19-
print(result)
2+
if not isinstance(n, int):
3+
raise TypeError("Input must be an integer")
4+
if n < 0:
5+
raise ValueError("Factorial is not defined for negative numbers")
6+
if n > 999:
7+
raise ValueError("Input too large - maximum value is 999")
8+
if n == 0:
9+
return 1
10+
result = 1
11+
for i in range(1, n + 1):
12+
result *= i
13+
return result

0 commit comments

Comments
 (0)