简体   繁体   English

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

[英]How to raise a Valueerror for a number that exceed a specific value in python?

I have tried to create a function that takes the factorial of a non-negative integer n.我试图创建一个函数,它采用非负整数 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.这部分工作得很好,但如果输入低于 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

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.在数学中,非负整数 n 的阶乘,用 n! 表示,是所有小于或等于 n 的正整数的乘积。 For example: 5!例如:5! = 5 * 4 * 3 * 2 * 1 = 120. By convention the value of 0! = 5 * 4 * 3 * 2 * 1 = 120。按照惯例,值为 0! is 1.是 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).如果输入低于 0 或高于 12,则抛出 ArgumentOutOfRangeException (C#) 或 IllegalArgumentException (Java) 或 RangeException (PHP) 类型的异常,或抛出 RangeError (JavaScript) 或 ValueError (Python) 或返回 -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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM