函数对于阶乘函数的递归函数返回None。

huangapple go评论59阅读模式
英文:

Function returning None for recursive function for factorial function

问题

我试图编写一个返回输入数字的阶乘的代码,但是当我运行它时,这段代码返回了"None",我不确定原因。

def factorial(num):
    if type(num) is not int():
        return None
    elif num == 0:
        return 1
    elif num < 0:
        return None
    else:
        return num * factorial(num - 1)

factorial5 = factorial(5)
print(factorial5)
英文:

I'm trying to write a code that returns the factorial of the input num but this code is returning "None" when I run it, I'm not sure why.

def factorial(num):
    if type(num) is not int():
        return None
    elif num == 0:
        return 1
    elif num &lt; 0:
        return None
    else:
        return num * factorial(num - 1)

factorial5 = factorial(5)
print(factorial5)

答案1

得分: 0

你的代码中多了一个括号,请看从int()改成int的修正:

def factorial(num):
    if type(num) is not int:
        return None
    elif num == 0:
        return 1
    elif num < 0:
        return None
    else:
        return num * factorial(num - 1)

factorial5 = factorial(5)
print(factorial5)

注意:使用Python3运行

120
英文:

You have an extra parenthesis .. see the correction from int() to int:

def factorial(num):
    if type(num) is not int:
        return None
    elif num == 0:
        return 1
    elif num &lt; 0:
        return None
    else:
        return num * factorial(num - 1)

factorial5 = factorial(5)
print(factorial5)

NOTE: ran with Python3

120

答案2

得分: 0

在您的代码中的问题在于条件 type(num) 不是 int()。正确的检查 num 是否不是 int 实例的方法是使用 isinstance() 函数来比较其类型是否为 int。

def factorial(num):
    if not isinstance(num, int):
        return None
    elif num == 0:
        return 1
    elif num < 0:
        return None
    else:
        return num * factorial(num - 1)

factorial5 = factorial(5)
print(factorial5)
英文:

The issue in your code lies in the condition type(num) is not int(). The correct way to check if num is not an instance of int is by comparing its type with int using the isinstance() function.

def factorial(num):
    if not isinstance(num, int):
        return None
    elif num == 0:
        return 1
    elif num &lt; 0:
        return None
    else:
        return num * factorial(num - 1)

factorial5 = factorial(5)
print(factorial5)

huangapple
  • 本文由 发表于 2023年6月12日 20:18:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/76456605.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定