Skip to content Skip to sidebar Skip to footer

Fibonacci In Python - Simple Solution

n1 = 1 n2 = 1 n3 = n1 + n2 for i in range(10): n1 + n2 print(n3) n1 = n2 n2 = n3 According to what I know, this should be the simplest way of outputting the first 10 d

Solution 1:

There are many issues with your code. And you should first learn and try as much as you can on your own. I am also a beginner so I know what you are thinking. For some quick edits to make it workable:

n1 = 0
n2 = 1
n3 = 0for i in range(10):
   n3 = n1 + n3
   print(n3)
   n1 = n2n2= n3
  1. The series starts with 0, you initialized it with 1.
  2. The update statement n3=n1+n2 is outside the loop, how will it update? What is happening here is n3 = 1 + 1 = 2 in your code stays the same and it doesn't change.

Solution 2:

n1 = -1
n2 = 1
n3 = n1 + n2
for i in range(10):
    n3 = n1 + n2
    print(n3)
    n1 = n2n2= n3

This should work. You failed to store sum of n1 and n2. You are simply printing n3 ie 2 ten times. And try initiating n1 and n2 from -1.

Post a Comment for "Fibonacci In Python - Simple Solution"