请问下这段代码中,不论把return更换为return 123、return num、return "h"等等,最后打印出的结果都不受return影响,return返回的值总是None
def sum_number(num):
print(num)
if num == 1:
return
# return 123
# return num
# return "h"
sum_number(num - 1)
print(sum_number(3))
def sum_number(num):
print(num)
if num == 1:
return 123
sum_number(num - 1)
print(sum_number(3))
def sum_number(num):
print(num)
if num == 1:
return "h"
sum_number(num - 1)
print(sum_number(3))
def sum_number(num):
print(num)
if num == 1:
return num
sum_number(num - 1)
print(sum_number(3))
最后的打印结果都是:
3
2
1
None
是我在对比另一段代码:
def sum_numbers(num):
if num == 1:
return 1
temp = sum_numbers(num - 1)
return num + temp
result = sum_numbers(100)
print(result)
结果:
5050
产生的疑问
抱歉,我一开始的回复有问题 。
def sum_number(num):
print(num)
if num == 1:
return 123
else:
k=sum_number(num - 1)
return k
print(sum_number(3))
3
2
1
123
这样就对了!主要是因为递归调用时,k=sum_number(num - 1)会一直不停的运行,需要一个合理的打断跳出,否则函数无合理返回就会显示None。所以递归调用时,条件变换两块都需要return。