简体   繁体   中英

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. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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