Recursive invocation of the python-function

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.