1

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.

2
  • 1
    How to debug small programs Commented May 15, 2019 at 8:21
  • 1
    IndexError: list index out of range your'e starting out with an empty array and trying to access index's on it. Commented May 15, 2019 at 8:22

4 Answers 4

4

You need to populate your list with first 2 numbers of Fibonacci sequence:

a = [0, 1]
Sign up to request clarification or add additional context in comments.

Comments

2

-2 and -1 indexes are not available if you don't set them in "a" list before using.

n = int(input())

def fib(n):
    a = [0, 1]
    if n <=1:
        return n
    else:
        for i in range(2, n):
            a.append(a[-1] + a[-2])
        return a[i]
print (fib(n))

Comments

1

Make these changes in your code

n = int(input())

def fib(n):
    a = [0,1]  # add these values to your array to intialize
    if (n <=1):
        return n
    else:
        for i in range(2, n):
            a.append(a[-1] + a[-2])
    return a  # change this also so that you can get all the values returned at the same time

print (fib(n))

Comments

1

Call this function to compute any Fibonacci series number

def Fibonacci(n): 
    if n<0: 
        print("Incorrect input") 
# First Fibonacci number is 0 
    elif n==0: 
        return 0
# Second Fibonacci number is 1 
    elif n==1: 
        return 1
    else: 
        return Fibonacci(n-1)+Fibonacci(n-2)

Or you can use this formula the formula for nth term in the fibonacci series.

Fn = {[(√5 + 1)/2] ^ n} / √5

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.