Home > Enterprise >  Fibonacci sequence stops kernel despite try/except
Fibonacci sequence stops kernel despite try/except

Time:11-15

I'm supposed to use a try/except block when finding the value of fibonacci(n):

def fibonacci(n):
    try:
        if n==0:
            return 0
        elif n==1 or n==2:
            return 1
    except ValueError:
        print("Input must be non-negative")
    return fibonacci(n-1)   fibonacci(n-2)

n=int(input("Enter the value of n: "))
print(fibonacci(n))

Here everything is working fine except the except block itself. Whenever I'm running the code, everything else is showing output correctly, but on the except case, I mean, if I enter a negative value the kernel just stops working, it shows the kernel is dead. I'm a bit confused about what's wrong here.

CodePudding user response:

First, your return is out of try/except that is why your kernel stops working, it returns no matter what input you will put through it. As you said in the comment you need to handle unexpected input. First, you need to verify your input before you let the Fibonacci function work with it. Hope that will be helpful.

from typing import Any

def fibonacci(n: Any) -> Any:
    try:
        n = int(n)
        if n >= 0:
            if n==0:
                return 0
            elif n==1 or n==2:
                return 1
            else:
                return fibonacci(n-1)   fibonacci(n-2)
        else:
            return "Input must be non-negative"
    except ValueError:
        return "Wrong type of input."

        
    

n = input("Enter the value of n: ")
print(fibonacci(n))

Hope this is what you are looking for. Should of used Union for return type hint. Sorry, my bad, had to add n = int(n) to a function. Tried to be more clever than I am and posted code before using it ;)

  • Related