I tried to be more verbose and write your functions like this:
def fib2(n):
ret = n and n < 2 or fib2(n-1) + fib2(n-2)
print "fib2({}) = {}".format(n, ret)
return ret
print fib2(4)
def fib3(m):
ret = m if m < 2 else fib3(m-1) + fib3(m-2)
print "fib3({}) = {}".format(m, ret)
return ret
print fib3(4)
It appears that fib2
tries to add boolean values to numbers, and that's why it's not correct. fib3
handles only numbers and is correct. But notice that it's not a recommended way to calculate Fibonacci numbers! If you try fib3(1000) it will run infinitely. It's better to start from 0 and 1 upwards, and not use recursion to calculate Fibonacci numbers.
I wrote a short function that calculates Fibonacci number #n for you:
def fib4(n):
a = 0
b = 1
for i in range(1, n + 1):
a, b = (b, a + b)
return a
print fib4(0)
print fib4(1)
print fib4(2)
print fib4(3)
print fib4(4)
print fib4(1000)
Notice it also works for n==1000
.