python递归
需求,计算1-10之间的和
# 方案一,while循环
my_int = 10
total = 0
while my_int > 0:
total = total + my_int
my_int = my_int - 1
print(total)
# 方案二,递归
total = 0
def my_sum(my_int):
global total
total = total + my_int
if my_int == 0:
return # 如果满足条件停止递归
my_int = my_int - 1
my_sum(my_int)
return total
print(my_sum(10))
# 递归代码优化
def my_sum(num):
if num == 0:
return num
return num + my_sum(num-1)
print(my_sum(10))
递归应用场景
# 递归应用场景:
# 需求:要求把下面列表当中的每一个值单独打印出来
my_list = [1, [2, 3, 4, [7, 65, [2, 3]]]]
def func1(new_list):
for i in new_list:
if isinstance(i, list):
func1(i)
else:
print(i)
func1(my_list)