-3

I am using python 3.8.8 and while running a simple program of Fibonacci it is giving me an error i.e. unsupported operand type(s) for +: 'NoneType' and 'NoneType'

def fibo(n):
if n <= 1:
    print("Hey! Please enter value greater than 1")
else:
    return((fibo(n-1)) + fibo(n-2))

nterms = 10
res = fibo(nterms)
print(res)
Sören
  • 1,803
  • 2
  • 16
  • 23
Utsav Upadhyay
  • 415
  • 6
  • 21
  • 2
    You are getting that error because the function doesn't return anything for the condition `n<=1`. Just replace that print statement with `return n`. – Zero May 22 '22 at 16:28
  • not at all @Sören – Utsav Upadhyay May 22 '22 at 16:28
  • Note that, via the recursion, `fibo` will eventually be called with `n` equal to 1. In which case, your error message will print and the function will exit with no `return` statement. In Python, if a function exits with no `return` statement, then `None` is implicitly returned. – Daniel Walker May 22 '22 at 16:29
  • 1
    Please don't alter your code's behavior after posting it. That makes it difficult for us to address any issues. – Daniel Walker May 22 '22 at 16:31
  • 2
    Notice that at no time does your code ever return a number. Ask yourself how addition could possibly work. – Mark May 22 '22 at 16:33
  • 2
    This code cannot produce the claimed result. Please post the real code. – John Gordon May 22 '22 at 16:34

1 Answers1

3

Add a return n to your code

def fib(n):
    if n<=1:
        return n 
    else:
        return(fib(n-1) + fib(n-2))

for i in range(10):
    print(f"fib({i}) = " + str(fib(i)))

gives

fib(0) = 0
fib(1) = 1
fib(2) = 1
fib(3) = 2
fib(4) = 3
fib(5) = 5
fib(6) = 8
fib(7) = 13
fib(8) = 21
fib(9) = 34
perperam
  • 432
  • 3
  • 10