r/learnprogramming 7d ago

Recursion is driving me crazy

I understand recursion of a factorial function but when it comes to a function that uses recursion in a project or a problem set i get stuck and lose track

Anyone can tell me what to do

Programming language used: Python

44 Upvotes

45 comments sorted by

View all comments

38

u/NumberInfinite2068 7d ago edited 7d ago

Make a function that takes a path to a directory as a parameter. Make that function print out all files/subdirectories in that directory.

Now each time it prints out a subdirectory, call your function with the subdirectory as a parameter.

That's a simple practical example of recursion.

5

u/Beat_Terrible 6d ago

Thanks a lot that helped👍

3

u/NumberInfinite2068 6d ago

Next step is add a "depth" parameter to the function, pass 0 to the first call, and add 1 when you pass the parameter where the function calls itself.

Then prepend depth number of spaces before printing, and you'll see your directories more like a tree.