Python Recursion

A function in Python can call itself. That’s what recursion is. And it can be pretty useful in many scenarios.

The common way to explain recursion is by using the factorial calculation.

The factorial of a number is the number n mutipli…


This content originally appeared on flaviocopes.com and was authored by flaviocopes.com

A function in Python can call itself. That’s what recursion is. And it can be pretty useful in many scenarios.

The common way to explain recursion is by using the factorial calculation.

The factorial of a number is the number n mutiplied by n-1, multiplied by n-2… and so on, until reaching the number 1:

3! = 3 * 2 * 1 = 6
4! = 4 * 3 * 2 * 1 = 24
5! = 5 * 4 * 3 * 2 * 1 = 120

Using recursion we can write a function that calculates the factorial of any number:

def factorial(n):
    if n == 1: return 1
    return n * factorial(n-1)

print(factorial(3)) #   6
print(factorial(4)) #  24
print(factorial(5)) # 120

If inside the factorial() function you call factorial(n) instead of factorial(n-1), you are going to cause an infinite recursion. Python by default will halt recursions at 1000 calls, and when this limit is reached, you will get a RecursionError error.

Recursion is helpful in many places, and it helps us simplify our code when there’s no other optimal way to do it, so it’s good to know this technique.


This content originally appeared on flaviocopes.com and was authored by flaviocopes.com


Print Share Comment Cite Upload Translate Updates
APA

flaviocopes.com | Sciencx (2021-01-05T05:00:00+00:00) Python Recursion. Retrieved from https://www.scien.cx/2021/01/05/python-recursion/

MLA
" » Python Recursion." flaviocopes.com | Sciencx - Tuesday January 5, 2021, https://www.scien.cx/2021/01/05/python-recursion/
HARVARD
flaviocopes.com | Sciencx Tuesday January 5, 2021 » Python Recursion., viewed ,<https://www.scien.cx/2021/01/05/python-recursion/>
VANCOUVER
flaviocopes.com | Sciencx - » Python Recursion. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2021/01/05/python-recursion/
CHICAGO
" » Python Recursion." flaviocopes.com | Sciencx - Accessed . https://www.scien.cx/2021/01/05/python-recursion/
IEEE
" » Python Recursion." flaviocopes.com | Sciencx [Online]. Available: https://www.scien.cx/2021/01/05/python-recursion/. [Accessed: ]
rf:citation
» Python Recursion | flaviocopes.com | Sciencx | https://www.scien.cx/2021/01/05/python-recursion/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.