英文:
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 < 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 < 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 < 0:
return None
else:
return num * factorial(num - 1)
factorial5 = factorial(5)
print(factorial5)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论