Python is a high level general purpose programming language which has a clear/easy learning curve. Python programming language is massively used in various domains like Artificial Intelligence, Data Science, Web Development, Utilities Tools and Scripts and many more
Python is a Programming language, and the default Python we use is written in C programming language which is also referred to as CPython (Python implementation in C). There are various implementation of Python Programming language i.e Jython(in JAVA), Skulpt(in JS) e.t.c
To make everything easy: We refer CPython as Python
Recursion means a technique in which a function calls itself. The function which is programmed in such a way that it can itself for some purpose is known as a recursive function.
The real-world example for a recursive function would be the reflection of two parallel mirrors placed facing each other
Example1
#printing the hello world 10 times using recursion.
def helloworld(n):
if(n>1):
print("Helloworld")
Helloworld(n-1) # self calling functions: recursions
else:
return
Helloworld(10)
Output
Helloworld
Helloworld
Helloworld
Helloworld
Helloworld
Helloworld
Helloworld
Helloworld
Helloworld
Helloworld
Example2
#Finding the factorial of a number using python.
def factorial(num):
if num==1 or num==0:
return 1
else:
return num*factorial(num-1)
print("10! = ",factorial(10))
print("5! = ",factorial(5))
Output
10! = 3628800
5! = 120
Example3
#Finding the Fibonacci series using python recursion.
def fibonacci(num):
if num==0 or num==1:
return num
else:
return fibonacci(num-1)+fibonacci(num-2)
for number in range(11): #fibonacci series length=10
print(fibonacci(number))
Output
0
1
1
2
3
5
8
13
21
34
55
Note:
By default, python limits the depth of recursion in order to avoid infinite recursion which may lead to stack overflow. So, in python maximum number of recursion depth is 1000 by default. After the completion of max depth, it will throw an error called RecursionError.
Example
def iamrecursion():
iamrecursion()
iamrecursion()
Output
Traceback (most recent call last):
[Previous line repeated 996 more times]
RecursionError: maximum recursion depth exceeded