0

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)
finefoot
  • 9,914
  • 7
  • 59
  • 102
D.Tomi
  • 71
  • 4
  • 2
    You tell us, what error or output are you getting and what do you expect? – MyNameIsCaleb Oct 19 '19 at 19:49
  • just change `for j in numbers` to `for j in range(len(numbers))` and it will be OK. – Peyman Oct 19 '19 at 19:56
  • @finefoot, Oh you are right. I just saw his/her mistake of taking `for i in L` as indexes, so just commented to point out for indexed you should do `for i in range(len(L))`. – Peyman Oct 19 '19 at 20:05

1 Answers1

1

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
finefoot
  • 9,914
  • 7
  • 59
  • 102