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)
3
  • 2
    You tell us, what error or output are you getting and what do you expect? Commented Oct 19, 2019 at 19:49
  • just change for j in numbers to for j in range(len(numbers)) and it will be OK. Commented Oct 19, 2019 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)). Commented Oct 19, 2019 at 20:05

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

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.