Python Learning (Recursive)

Source: Internet
Author: User

I. Recursion

Recursion is the function itself calling itself

Recursive maximum usable depth in Python is 997

Recursion can be used to traverse various tree structures

#to view the contents of a file within a path using a recursive methodImportOsFilePath='d:\ Information Download'   #the file path to opendefRead (Filepath,n):#n is the recursive depth, which is used to control the number of indentsit = Os.listdir (filepath)#opens the file according to the given file path, and the returned it is an iterative object    #print ("__next__" in Dir (it)) #it对象中不包含__next__函数, so not an iterator     forElinchIt#iterate over the files in the given file path and print out the file namefp = Os.path.join (Filepath,el)#content within the file path if it is still a folder, you need to use recursion to open the folder inside again, so you need to combine the file path        ifOs.path.isdir (FP):#determine whether content within a path is a folder-invariant notation            Print('\ t'*n,el) Read (Fp,n+1)#re-call the secondary function, but the parameter is the new path name        Else:#the content in the file path is not a folder, you do not need to open it again, print the file name directly            Print('\ t'*n,el) Read (filepath,0)#The initial recursion depth is 0

Python Learning (Recursive)

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.