Recursion Function In Python
What is recursion?
Recursion Function
In Python:
The recursion is a process where function calls itself
to perform a task. The calling of function itself is done repeatedly until certain
condition met. Recursion is process in which function calls directly or
indirectly.
Advantages of Recursion Function:
1.
Breaking down a
function into smaller sub problems to reach to the base problem.
2.
It is very simpler
than other nested functions.
3.
Code is very
simple and effective than other normal functions.
Syntax of Recursive Function:
def function_name(): # Function definition
Statement
Statement
Recursive function_call() # Recursion
Function_name() # Function call
Def keyword is used to define the function. Function_name is
the name of function given by user. Function body includes statements and
recursive function call. The function call itself until certain condition
satisfy. Then function is called to invoke the user defined function and function body executed.
For example,
Factorial of given number using Recursive function in Python
print("Demonstration
of Recursive Function in Python")
print("______________________________________\n")
def
factorial(n): #function definition
if n==0:
return 1
else:
return n*factorial(n-1) # Recursion
n=int(input("Enter
number:"))
print(f"The
factorial of {n} is:",factorial(n)) # Function call
Output:
Demonstration of
Recursive Function in Python
_____________________________________________
Enter number:5
The factorial of 5
is: 120
In above example factorial is user defined function
with argument n. User input is stored into n to calculate factorial of n.
Function body have processing statements which have conditional statement. If n is exactly equals to 0. Then compiler will return 1. If condition becomes false means
n is greater than 0 then the function calls itself with argument n-1 until
condition satisfy. This process is done repeatedly until condition satisfy.
0 टिप्पण्या
कृपया तुमच्या प्रियजनांना लेख शेअर करा आणि तुमचा अभिप्राय जरूर नोंदवा. 🙏 🙏