I have tried to create a function that takes the factorial of a non-negative integer n. And that part is working great, but I also have to create a ValueError if input is below 0 or above 12 which doenst work.
def factorial(n):
countdown = n
factorial_sum = 1
while True:
try:
if n == 0:
return 1
if n < 0 or n > 12:
raise ValueError
except ValueError:
return 'Error'
if (countdown / n) > 0 and n <= 12:
factorial_sum = factorial_sum * countdown
countdown = countdown - 1
if (n - countdown + 1) == n:
return factorial_sum
elif (n - 1) == 0:
return factorial_sum
The challenge is from codewar and state:
In mathematics, the factorial of a non-negative integer n, denoted by n!, is the product of all positive integers less than or equal to n. For example: 5! = 5 * 4 * 3 * 2 * 1 = 120. By convention the value of 0! is 1.
Write a function to calculate factorial for a given input. If input is below 0 or above 12 throw an exception of type ArgumentOutOfRangeException (C#) or IllegalArgumentException (Java) or RangeException (PHP) or throw a RangeError (JavaScript) or ValueError (Python) or return -1 (C).
All answers will be greatly appreciated
Replace
try:
if n == 0:
return 1
if n < 0 or n > 12:
raise ValueError
except ValueError:
return 'Error'
by
if n == 0:
return 1
if n < 0 or n > 12:
raise ValueError