如何在python中为超过特定值的数字引发Valueerror?

2024-04-19 20:00:58 发布

您现在位置: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

挑战来自codewar和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).

所有答案将不胜感激


Tags: oroftheto函数inputreturnif