HI @Pragyan_Srivastava
Recursion is just like a loop, but in recursion, we call a function within the same function, which creates a loop.
A loop has four essential component
- Initialization/starting point
- Condition/limit
- Rate of change in the variable used in 1 and 2
- Statements to be iterated
Let me explain it a very simple example of counting the number of digits.
Using while loop
number = 367485387
counter = 0 # Component 1: Initialization
while not (number == 0): # Component 2: Condition
number = int(number/10) # Component 3: Change in the in the variable used in 1 and 2
counter += 1 # Component 4: Statements to be iterated
print(counter)
Let’s write its recursive function
def numberOfDigits(number, counter):
if not (number == 0): # Component 2: Condition
return numberOfDigits(int(number/10), counter+1): # Component 3: Change in the in the variable used in 1 and 2 and Component 4: Statements to be iterated
else:
return counter
print(numberOfDigits(367485387, 0)) # Component 1: Initialization
I hope my response was helpful but if there are still any queries then do let me know. Thanks.