What is recursion in Python?

Updated: May 18


Recursion is the process of defining something in terms of itself. A recursive function is a function defined in terms of itself via self-referential expressions. This means that the function will go on to call itself and repeat its actions whereas some condition is met to return a result.

Example:

def fact(x):

if x == 1:

return 1

else:

return (x * fact(x-1))

num=int(input("Enter the Number: "))

print("The factorial of", num, "is", fact(num))

Output:

Enter the Number: 3

The factorial of 3 is 6


Advantages of Recursion

  • Recursive functions make the code look clean and stylish.

  • A complex task can be broken down into simpler sub-problems using recursion.

  • Sequence generation is easier with recursion than using some nested iteration.

Disadvantages of Recursion

  • Occasionally the logic behind recursion is hard to follow through.

  • Recursive calls are costly because they are used a lot of memory and time.

  • Recursive functions are not easy to debug.