Home > Blockchain >  When I attempt to execute my recursive function with odd numbers ,i have a kern problem
When I attempt to execute my recursive function with odd numbers ,i have a kern problem

Time:11-10

There is a problem with odd numbers. When I run the function on even numbers, the code works.

    #recursive demo function1
    #Even nums
    def evenNum(num):
        if num % 2 != 0:
            print("enter a even number")
        if num == 2:
            return num
        else:
            return evenNum(num-2)        
    evenNum(5)
 output : Canceled future for execute_request message before replies were done

CodePudding user response:

The second if should be changed to elif. When number is odd it prints "Enter a even number" and then compares it to 2. As it is different, it calls the function again.

Here is fixed code

    def evenNum(num):
        if num % 2 != 0:
            print("enter a even number")
        elif num == 2:
            return num
        else:
            return evenNum(num-2)        
    evenNum(5)

Btw. make sure the number is greater than 0.

CodePudding user response:

#recursive function1
#positive Even nums
def evenNum(num):
        print(num)
        if num % 2 != 0:
            return print("enter an even number")
        elif num == 2:
            pass
        else:
            return  evenNum(abs(num)-2)        
evenNum(5)

Thank you for your valuable advice. I learned some things about return and kern error.

  • Related