A Simple Python Recursion Example

Published by Brandon on

Let’s look at an example of a recursive function in python, which basically means, a function that calls itself.

The thing about recursive functions is that they will have to end at some point or they will just continuously loop. In the example below, we will talk about a flaw of this recursive function if the user gives us the wrong input.

A Recursive Factorial Function

Try this script on your own and pass in values to the function. Notice how this function will eventually end, as long as you pass in a positive number. The reason that’s important is because when the recursive function is called, it decreases the value by 1 unless the number passed in is 1, then the recursion will stop.

But, since the recursion only stops when the value passed in is 1, if you pass in a negative number, it will never end.

def factorial(num):

    if num == 1:
        return 1
    else:
        return (num * factorial(num - 1))


print(factorial(5))

So what makes this function a recursive function? In the else statement, the return statement calls that same function. When we pass in the value 5, eventually, that return statement will look like this:

return (5 * 4 * 3 * 2 * 1)

What if we Pass in a Negative Number?

If we do pass in a negative number into this, python will tell us to slow our roll as the maximum recursion depth has been exceeded.


print(factorial(-1))

[Previous line repeated 995 more times]
  File ".\factorial.py", line 3, in factorial
    if num == 1:
Categories: Python

0 Comments

Leave a Reply

Avatar placeholder

Your email address will not be published. Required fields are marked *