What is recursion in Python with Examples?
top of page

What is recursion in Python with Examples?

Updated: Feb 17, 2022


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.

In other words we can say that it is a programming technique in which a function calls itself from its own body definition. It is similar to loop because it repeats the same code a number of times.

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.

Example:

Write a program to input a number and calculate its factorial.

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

Example 2:

Write a program to input a number and print its table up to 10 terms.

Program:

def table(num):

for i in range(1, 11):

print(num, 'x', i, '=', num*i)

return

n = int(input("Enter number: "))

table(n)

Output:

Enter number: 5

5 x 1 = 5

5 x 2 = 10

5 x 3 = 15

5 x 4 = 20

5 x 5 = 25

5 x 6 = 30

5 x 7 = 35

5 x 8 = 40

5 x 9 = 45

5 x 10 = 50

Example 3:

Python program calculates the sum of the first N Natural numbers using recursive function calls.

def sum(n):

if n==1:

return 1

else:

return (n + sum(n-1))

num=int(input("Enter a number : "))

s=sum(num)

print("The sum of natural numbers is ", s)

Output:

Enter a number : 4

The sum of natural numbers is 10





19 views0 comments

Recent Posts

See All

Tell function in python with example

Tell () function can be used to get the position of file handle and returns current position of file object where as Seek () function is used to change the position of the file handle to a given speci

Seek function in python with example

Seek () function is used to change the position of the file handle to a given specific position in python. File handle such as a cursor which defines from where the data has to be read or written in t

bottom of page