#๐Ÿ”’ Fibonacci Sequence for loop

9 messages ยท Page 1 of 1 (latest)

naive gulch
#

Hi, for my school homework we are supposed to make a for loop of the fibonacci sequence. The sequence is supposed to stop at the 10th index in the sequence. Here's my code so far;

n = 10

#// BEGIN_TODO [Fibonacci_number] Fibonacci number
fibonacci: int = 1
for i in range(fibonacci):
    next_number1 = (i - 1)
    next_number2 = (i - 2)
    fibonacci = next_number1+next_number2
    print("the fibonacci number in position " + str(i) + " corresponds to " + str(fibonacci) + ".")
    if i == 11:
        break
#// END_TODO [Fibonacci_number]

The output:

the fibonacci number in position 0 corresponds to -3.
the fibonacci number in position 1 corresponds to -1.
the fibonacci number in position 2 corresponds to 1.
the fibonacci number in position 3 corresponds to 3.
the fibonacci number in position 4 corresponds to 5.
the fibonacci number in position 5 corresponds to 7.
the fibonacci number in position 6 corresponds to 9.
the fibonacci number in position 7 corresponds to 11.
the fibonacci number in position 8 corresponds to 13.
the fibonacci number in position 9 corresponds to 15.

Please just tell me what's exactly going on and why it outputs this way. Don't give me any raw code as that's against the school's rules. Thank you.

wild martenBOT
#

@naive gulch

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

rain jay
#

There's a few things happening here:

  • the for-loop counts i from 0 onward
  • when i=0, you add -1 and -2 to get -3
#

What you actually want is for the for-loop to run 10 times. I think your output isn't from exacty the code you have, but some recent revision.

To run 10 times I would be using range(n) because n=10, and range(10) counts from 0 through to 9 (which is 10-1 - Python ranges are half open - including the first number and excluding the final number).

#

And i suspect you makde than change to get the out putyou got.

#

You don't need the if i == 11: because the range will produce the right number of iterations.

#

It seems to me that your fibonacci variable is the "current" fibonacci value. So you should run your print() immediately at the top of the loop. Then compute the next value.

wild martenBOT
#
Python help channel closed

This help channel has been closed and it's no longer possible to send messages here. If your question wasn't answered, feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.