Python循环和返回模式



我正在尝试这个代码。

函数incre_test是递归的,除非它满足条件。

我期望5作为结果,但它返回None

这种模式的最佳实践是什么?

def incre_test(i):
if i > 4:
return i
i = i + 1
incre_test(i)
res = incre_test(0)
print(res) // why None???

试试这个:

def incre_test(i):
while not i == 5:
i+=1
return i
res = incre_test(0)
print(res)

您必须使用while <bool>:循环来运行脚本(在本例中为i+=1(,直到给定的条件为true。

在函数中使用循环可能会使更好

def incre_test(i):
while i < 5:
i += 1
return i

这是因为除非参数大于4,否则函数不会返回任何值,所以您所要做的就是在函数的递归调用上添加一个return语句,如下。。。

def incre_test(i):
if i > 4:
return i
return incre_test(i+1)
res = incre_test(0)
print(res)

输出:-

5

最新更新