D.Tomi
D.Tomi

Reputation: 71

What is the problem about my fibonacci python code?

If you could look at my code.

numbers = [1,2]
times = int(input("How many numbersM (minimum is 2)"))
def fibonacci(numbers, times):
    for i in range(0, times):
        for j in numbers:
            numbers.append( numbers[j] + numbers[j+1])
        print(numbers[i])
fibonacci(numbers, times)

Upvotes: 0

Views: 73

Answers (1)

finefoot
finefoot

Reputation: 11382

If you run your code like that, you will get

IndexError: list index out of range

because for j in numbers: is a loop over the values in numbers which contains value 1 which is an index out of range when you try to access numbers[j+1] because there is no numbers[2] at this point. Why do you need that second for loop in there anyway? You will access the last and second-to-last values with numbers[i] and numbers[i+1]. No need to loop over the other values of your list.

I have removed that loop and if you run your code like this:

numbers = [1,2]
times = int(input("How many numbersM (minimum is 2)"))
def fibonacci(numbers, times):
    for i in range(0, times):
        numbers.append( numbers[i] + numbers[i+1])
        print(numbers[i])
fibonacci(numbers, times)

You'll get something like this, for example:

How many numbersM (minimum is 2)5
1
2
3
5
8

Upvotes: 1

Related Questions