如何为超过 python 中特定值的数字引发 Valueerror?
How to raise a Valueerror for a number that exceed a specific value in python?
我试图创建一个函数,它接受非负整数 n 的阶乘。那部分工作得很好,但如果输入低于 0 或高于 12,我还必须创建一个 ValueError,这确实有效。
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
挑战来自代码战和状态:
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).
所有答案将不胜感激
替换
try:
if n == 0:
return 1
if n < 0 or n > 12:
raise ValueError
except ValueError:
return 'Error'
来自
if n == 0:
return 1
if n < 0 or n > 12:
raise ValueError
我试图创建一个函数,它接受非负整数 n 的阶乘。那部分工作得很好,但如果输入低于 0 或高于 12,我还必须创建一个 ValueError,这确实有效。
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
挑战来自代码战和状态:
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).
所有答案将不胜感激
替换
try:
if n == 0:
return 1
if n < 0 or n > 12:
raise ValueError
except ValueError:
return 'Error'
来自
if n == 0:
return 1
if n < 0 or n > 12:
raise ValueError