Example of Recursion | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Example of Recursion

5th Nov 2016, 11:08 AM
Djaber Meghar
Djaber Meghar - avatar
2 Answers
+ 2
The most basic example of recursion is the facorial function: def factorial(n): if n == 1: return 1 else: return n * factorial(n-1) You can see the base case, where n == 1 is checked, without this one it would be an infinite loop. The base case is a necessary case in recursion. The other necessary thing in recursion is the fact that for some cases, the function calls itself, in order to loop.
5th Nov 2016, 11:16 AM
Pierre Varlez
Pierre Varlez - avatar
+ 2
Though not a Python example, contrast can really help. This shows a very simple recursive factorial against the more complex iterative version. https://chortle.ccsu.edu/java5/Notes/chap72/ch72_8.html
5th Nov 2016, 11:34 AM
Kirk Schafer
Kirk Schafer - avatar