I was trying to write a program to compute the Fibonacci number using Python:
n = int(input())
def fib(n):
a = []
if (n <=1):
return n
else:
for i in range(2, n):
a.append(a[-1] + a[-2])
return a[i]
print (fib(n))
However, I can't print out the expected result. For example, after I typed in the number 8, the following message popped up:
Traceback (most recent call last):
File "fibonacci.py", line 11, in <module>
print (fib(n))
File "fibonacci.py", line 9, in fib
a.append(a[-1] + a[-2])
IndexError: list index out of range
What went wrong in the process? Thanks in advance.
IndexError: list index out of rangeyour'e starting out with an empty array and trying to access index's on it.