Recursive invocation of the python-function

Source: Internet
Author: User

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

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.