【发布时间】:2023-03-25 13:25:02
【问题描述】:
这是一个用于求一个数的因数之和的代码。查找因子函数中返回的列表是我猜 sum 函数无法访问的,因为当我打印列表时,它给出了正确的列表。
我收到的错误是:TypeError: object of type 'NoneType' has no len()
def perfect_number(n):
def sum(list,counter,value):
if counter==len(list):
print (value)
else:
sum(list,counter+1,value+list[counter])
def find_factors(n,a,list):
if (a==n):
print (list,len(list))
return (list)
elif (n%a )== 0:
list.append(a)
find_factors(n,a+1,list)
elif (n%a) !=0:
find_factors(n,a+1,list)
xyz = find_factors(n,1,[])
return sum(xyz,0,0)
perfect_number(6)
【问题讨论】:
-
首先,不要使用内置函数作为变量/函数名
-
但是,错误是什么??
-
好吧,
find_factors不返回任何内容,因此xyz是None。 -
但为什么不返回列表?当我使用返回列表命令时!
-
你只在一个内部递归调用中返回它,但它不会传播到最外面的调用。尝试在对
find_factors的所有递归调用之前添加 return
标签: python