我打算用这个函数递归地乘以两个数字。我意识到这可能远非最佳。为什么我的此号函数print rec_mult(15, 1111)
打印None
而不是16665
?
def rec_mult(x, y, tot=0, inc=0):
if int(x) == 0:
return tot
else:
x = str(x)
tot += int(x[(-1+inc):]) * y
x = x[:(-1+inc)] + "0"; inc -= 1
rec_mult(x, y, tot, inc)
答案 0 :(得分:5)
递归调用函数时必须return
,
def rec_mult(x, y, tot=0, inc=0):
if int(x) == 0:
return tot
else:
x = str(x)
tot += int(x[(-1+inc):]) * y
x = x[:(-1+inc)] + "0"; inc -= 1
return rec_mult(x, y, tot, inc) # <-- return here
print rec_mult(2, 10) # 20