In this tutorial, we discuss Python language Recursive function.
When a function calls itself it is called as recursion. The python language allows creating the recursive function to perform a special task
The following example explains how to find the adding of the limited natural numbers using the recursive function
The following is an example of the recursive function to total a series of the integer numbers
Program 1
def sum_Num(num): if num == 0: return 0 else: return num + sum_Num(num-1) print("Sum of the first 100 numbers is",sum_Num(100)) print("Sum of first 500 numbers is",sum_Num(500))
When the above code executed, it produces the following results
Sum of the first 100 numbers is 5050 Sum of first 500 numbers is 125250
In the above example, to find the total of given numbers, when we passing the argument of the positive integer of this function, it will recursively call itself decreasing one by one until it becomes one from a given number.
Program 2
following example explain how to find the factorial of a number using a recursive function in python.
factorial of a number is the product of the all integer from one to until the given number
For example, the factorial of 5 is 1*2*3*4*5n=120
#This is a example for find factorial #using recursive function in Pyton def calc_fact(n): if n==1: return 1; else: return(n*calc_fact(n-1)) num= int(input("Enter the number for find factorial: ")) # take input from user for find factorial print("The factorial of ",num," is", calc_fact(num)) #display factorial
When the above code executed, it produces the following results
Enter the number for find factorial: 5 The factorial of 5 is 120
In the above example, calc_fact() is a recursive function as it calls itself to find factorial.
Factorial of n is the product of all the integer from 1 to the factorial of n is 1*2*3*4……..*n-1*n.
In the above example, to find the factorial of a given number, when we pass the argument as the positive integer of this function, it will recursively call itself decreasing one by one until it becomes one from a given number
Suggested for you
Find factorial using recursion in Python
PHP Star Triangle pattern program In this tutorial, we will discuss about PHP Star Triangle…
PHP Full Pyramid pattern program In this tutorial, we will discuss about PHP Full Pyramid…
5 methods to add two numbers in Java In this tutorial, we will discuss the…
Python full Pyramid star pattern program In this tutorial, we will discuss the concept of…
Write a function or method to convert C into F -Entered by the user In…
How to write a function or method to convert Celsius into Fahrenheit In this tutorial,…