the recursive invocation, as the name implies, calls the function inside the function (calling itself), usually using it to calculate factorial, accumulate, etc.Note:-Must have the final default resultIf n ==0, (cannot always call itself if there is no possibility of causing a dead loop)-Recursive parameters must converge to the default resultfunc (n-1) Example 1: Calculate factorial of 5
# !/usr/bin/env python def func (n): if n = = 0: return 1 else: return N * func (n-1
print func (5)
Example 2: Calculation of 1 to 100 and
# !/usr/bin/env python def = 0 if n = = 0: return 0 Else: retur N N + func (n-1print func (100)
Example 3: Print all file names in the directory in a recursive way
# !/usr/bin/env python Import OS Import def = Os.listdir (n) for in Lsdir: if Os.path.isfile (Os.path.join (n,i)): Print Os.path.join (n,i) Else : Listdir (Os.path.join (n,i)) Listdir (sys.argv[1])
Improved version:
#!/usr/bin/env python ImportOSImportSYSdefprint_file (path): Lsdir=os.listdir (path) files= [I forIinchLsdirifOs.path.isfile (Os.path.join (path,i))] Dicts= [I forIinchLsdirifOs.path.isdir (Os.path.join (path,i))]ifFiles: forIinchFiles:PrintOs.path.join (path,i)ifdicts: forFinchDicts:print_file (Os.path.join (path,f)) Print_file (sys.argv[1])
modules usedOs.pass.isdir ()-Determine if the following file is a directory, if yes returns True (cannot determine if the directory exists, does not exist and will return false)Os.path.isfile ()-To determine if the file that follows is a file, yes to return true (cannot determine if the file exists, does not exist and will return false)Os.path.join ()-connect the path in parentheses (file)os.path.join ('/etc/', ' passwd ', ' abc ')---->/ETC/PASSWD/ABC NotePython3 The default recursion depth cannot exceed 100 levels
Recursive invocation of the python-function