Computer Science

Can you find an error or problem with the below code? Think about what happens if we evaluate check(3). What output would be produced by Python? Explain the reason(s) behind the output.

def check (n) :
    if n <=1:
        return True
    elif n % 2 == 0:
        return check (n/2) 
    else:
        return check (n/1)

Python Functions

2 Likes

Answer

Yes, there is a error in the provided code. If we evaluate check(3), it will result in an infinite recursion and eventually lead to an error.

This happens because when check(3) is called, the function first checks if n is less than or equal to 1, which is not the case. Since n is odd (i.e., n % 2 == 1), it enters the else block and calls check(n/1) which leads to the same value of n being passed recursively to the function without any change. As a result, the function keeps calling itself with the same value of n, leading to an infinite loop of recursion.

Answered By

2 Likes


Related Questions