It's because for n=2 the result is f(0)+f(1)= 0+1 =1 and not 2 so return 1 so you can remove that condition, also the sum code is useless and it not reachable, so it becomes :
def fib(n):
if n == 0:
return 0
elif n == 1:
return 1
return fib(n - 1) + fib(n - 2)
# can be shorten with python if/else inline syntax
def fib(n):
return n if n <= 1 else fib(n - 1) + fib(n - 2)
You can find others implementations here : How to write the Fibonacci Sequence?
TO get the sum of fibo values, you may store the values, to not count them a lots of time, solution : array. And if you manage to use it several time, get the array out of the function, here is an example of how to use it to be performant
fibonacci_numbers = [0, 1]
def fibo_setup(max_value=10):
"""Compute the values until a limit, and store in a list"""
for i in range(len(fibonacci_numbers), max_value):
fibonacci_numbers.append(fibonacci_numbers[i - 1] + fibonacci_numbers[i - 2])
def fibo(n):
"""Retrieve a fibo value using the array, compute if not present"""
if len(fibonacci_numbers) < n:
fibo_setup(n + 1)
return fibonacci_numbers[n]
def fibo_sum(n):
"""Get the sum of fibo values, and before it checks that the array is filled"""
fibo_setup(n)
return sum(fibonacci_numbers[:n])
if __name__ == '__main__':
fibo_setup(10)
print(fibo(12))
print(fibo_sum(15))