The recursive invocation, as the name implies, calls the function inside the function (itself calls itself), usually using it to calculate the factorial, accumulate, etc. note:-Must have the last default result if n ==0, (cannot always call itself, if there is no possibility of causing a dead loop)-the recursive parameter must converge to the default result func (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 func (n): sum = 0 if n = = 0:return 0 else:return n + func (n-1) print func (100)
Example 3: Print all file names in the directory in a recursive way
#!/usr/bin/env python import osimport sys def listdir (n): Lsdir = Os.listdir (n) for I 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 import osimport sys def print_file (path): Lsdir = os.listdir (path) files = [i-I in Lsdir if O S.path.isfile (Os.path.join (path,i))] Dicts = [i-I in Lsdir if Os.path.isdir (Os.path.join (path,i))] if files:f Or I in Files:print os.path.join (path,i) if Dicts:for f in Dicts:print_file (Os.path.join (path,f)) PR Int_file (Sys.argv[1])
Module Os.path.isdir ()-Determines whether the following file is a directory, returns True (cannot determine whether the directory exists, does not exist, or returns false) Os.path.isfile ()-Determines whether the following file is a file, or returns True ( Cannot determine if the file exists, does not exist and will return false) Os.path.join ()-The path in the parentheses (file) os.path.join ('/etc/', ' passwd ', ' abc ')---->/etc/passwd/ab C Note Python3 The default recursion depth cannot exceed 1000 levels
Recursive invocation of the python-function