educative.io

Educative

Recursive function

I am unable to understand Recursive Example.Please elaborate it!!


Type your question above this line.

Course: https://www.educative.io/collection/10370001/5473789393502208
Lesson: https://www.educative.io/collection/page/10370001/5473789393502208/4757323404804096

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

  1. Initialization/starting point
  2. Condition/limit
  3. Rate of change in the variable used in 1 and 2
  4. 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.