为什么我在这个简单的 python 程序中得到结果 NONE?



我正在学习python 3。我希望这个程序将一个递减的整数序列相加。相反,我没有得到。

如果这是一个错误,我也许能够弄清楚我做错了什么,但在这种情况下,我被难住了。

def add_many_things(init_value):
accumulator = 0
while init_value > 0 :
accumulator = accumulator + init_value
init_value = init_value - 1
result = add_many_things(37)
print(f"{result}")

试试这个:

def add_many_things(init_value):
accumulator = 0
while init_value > 0 :
accumulator = accumulator + init_value
init_value = init_value - 1
return accumulator
result = add_many_things(37)
print(f"{result}")

您错过了将return语句添加到add_many_things函数。
Python 允许这种情况并计算返回值以None

return accumulator添加到函数中。您正在尝试分配函数的结果:

结果 = add_many_things(37(

但是您的add_many_things()函数不返回值。在函数末尾添加 return 语句会将accumulator的值传递回调用方。

最新更新