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.



Recent Posts

See All

Python Modules

A module is a file containing Python definitions and statements. A module can characterize functions, classes and variables. A module can likewise incorporate runnable code. Gathering related code int

Command Line Arguments in Python

Command Line Arguments are the arguments that are specified after the name of the program in the command line shell of the operating system. Python gives different ways of dealing with these types of