A few issues:
The error is caused by num1 = li[-1]
: at that time you have not given li
a value yet (except in the erroneous case where x
is 1).
The inner loop does not modify num1
or num2
, so you would keep adding the same values. Combined with the first issue, you should move the assignments to num1
and num2
into the loop.
The first two Fibonacci numbers are not 1 and 2, but 0 and 1. So initialise with li = [0, 1]
. See also In the Fibonacci sequence, is fib(0) 0 or 1 ?
When x
is 1, the execution also continues into the else
block. If you change the second if
with elif
this will not happen.
You should probably also deal with the case when x
is 0.
Taking all that together you get:
def fib_list(x):
if x == 0:
li = []
elif x == 1:
li = [0]
elif x == 2:
li = [0,1]
else:
li = [0,1]
for n in range(2,x):
num1 = li[-1]
num2 = li[-2]
li.append(num1+num2)
return li
It is of course possible to write this more succinctly:
def fib_list(x):
li = [0,1]
if x <= 2:
return li[:x]
for n in range(x-2):
li.append(sum(li[-2:]))
return li
And when you consider that you only need the sum, there is no reason to actually build a list:
def fib_sum(x):
if x < 2:
return 0
a = 0
b = total = 1
for n in range(x-2):
a, b = b, a + b
total += b
return total
The results are as expected:
x | sum | Fib
---+-----+-----------------
0 | 0 | []
1 | 0 | [0]
2 | 1 | [0,1]
3 | 2 | [0,1,1]
4 | 4 | [0,1,1,2]
5 | 7 | [0,1,1,2,3]
6 | 12 | [0,1,1,2,3,5]
7 | 20 | [0,1,1,2,3,5,8]
8 | 33 | [0,1,1,2,3,5,8,13]