KnowledgeBoat Logo

Computer Science

Figure out the problem with the following code that may occur when it is run.

def recur(p): 
   if p == 0:
       print ("##")
   else:
       recur(p) 
       p = p - 1

Python Functions

1 Like

Answer

The error in the provided code is that inside the else block the value of p is modified after the recursive call. This leads to an infinite recursion because p remains the same in each recursive call, never reaching the base case (p == 0) and causing the program to enter an infinite loop.

Explanation

The corrected code is:

def recur(p):
    if p == 0:
        print("##")
    else:
        recur(p - 1)

In this corrected version, p is decremented by 1 in each recursive call, ensuring that the recursive process eventually reaches the base case where p == 0 and terminates the recursion.

Answered By

3 Likes


Related Questions