python学习笔记9-函数递归调用(自己调用自己)[root@localhost ~]# vim factorial.py
#!/usr/bin/python
def factorial(n):
sum=1
for i in range(1,n+1):
sum *=i
return sum
print factorial(5)
[root@localhost ~]# python factorial.py
120
递归调用
递归注意事项:
必须有最后的默认结果 if n==0
递归参数必须向默认结果收敛的:factorical(n-1)
乘法递归[root@localhost ~]# vim factorial.py
#!/usr/bin/python
def factorial(n):
if n==0:
return 1
else:
return n * factorial(n-1)
print factorial(5)
[root@localhost ~]# python factorial.py
120
加法递归[root@localhost ~]# vim factorial.py
#!/usr/bin/python
def factorial(n):
if n==0:
return 0
else:
return n + factorial(n-1)
print factorial(100)
[root@localhost ~]# python factorial.py
5050
练习:递归列出目录里面的文件[root@133 function]# vim recursion.py
#!/usr/bin/python
import os
import sys
def print_files(path):
lsdir = os.listdir(path) #列出文件
dirs = [i for i in lsdir if os.path.isdir(os.path.join(path,i))] #采用列表重写方法,isdir返回布尔值,判断后边是不是一个目录,是,返回True
files = [i for i in lsdir if os.path.isfile(os.path.join(path,i))]#isfile返回布尔值,判断后边是不是一个文件,是,返回True
if files: #判断文件有么有?没有的话是none,if none false,不执行,否则有文件,if files 为true,有的话把每个文件列出出来
for f in files:
print os.path.join(path,f) #添加文件的路径,通过path和f找到文件路径:
if dirs: #判断子目录有么有?没有子目录,if none返回false,有子目录,if dirs返回True,有的话把每个子目录调用递归函数
for d in dirs:
print_files(os.path.join(path,d)) #添加目录的路径,通过path和d找到目录路径:
print_files(sys.argv[1])
这里使用了列表重新,举例:
[i for i in range(10) if i%2==0] 这里我只要偶数的元素
[root@133 function]# python recursion.py /opt/python #sys.argv[1]是 /opt/python
/opt/python/README.md
/opt/python/function/def_function.py
/opt/python/function/recursion.py
/opt/python/function/factorial.py
/opt/python/function/def_ifnumber.py
/opt/python/function/global_inter.py
/opt/python/function/return.py
/opt/python/function/proc.py
/opt/python/filevalue/2.py
/opt/python/filevalue/mac.py
/opt/python/filevalue/if.py