1、递归函数的特点:
- 调用自身
- 函数内部有结束条件
2、区分递归函数
1)不是递归函数
# 无结束条件一直调用自身
def func1(x):
print(x)
func1(x - 1)
# 无结束条件一直调用自身
def func2(x):
if x > 0:
print(x)
func2(x + 1)
2)递归函数
def func3(x):
if x > 0:# 结束条件
print(x)
func3(x - 1)
def func4(x):
if x > 0:# 结束条件
func4(x - 1)
print(x)
def func5(x):
if x > 0:结束条件
func5(x - 1)
print(x)
3、递归函数的调用过程(代码至上而下执行)
无返回值的情况
1)func3:
E:\Python\install_path\python.exe F:/pychrom_python/python/Code/python复习/1.递归.py
3
2
1
2)func4:
E:\Python\install_path\python.exe F:/pychrom_python/python/Code/python复习/1.递归.py
1
2
3
有返回值的情况:
计算阶乘
def Factorial(x):
if x == 1:
return x
return x * Factorial(x - 1)
print(Factorial(3))
# 结果
6
进程已结束,退出代码为 0