How to Write the Fibonacci Sequence code in Python.

Generally in mathematics, the Fibonacci numbers or Fibonacci sequence are the numbers in the following integer sequence. i.e 1,1,2,3,5,8,13... or in a more mordern convension it starts from 0,1,1,2,3,5,8,13...
looking at the above sequence, you discover something(using the first sequence):
The sequence is initialized with the starting 1, --> it then adds to nothing or say Zero( which is not seen to get another 1), resulting to {1,1}, which also adds up to get the next element of the sequence (1+1=2), hence we now have a sequence{1,1,2},to get the next element of the sequence, we add (1+2), and thus for every position of the sequence, say (i), the value of the element is {the value of [(i -1)'s value + (i-2)'s value]. As in the above we have
Note: 1 is regarded as the default start value

1     1       2       3        5        8        13       21

1, (1+0=1), (1+1=2), (1+2=3), (2+3=5), (3+5=8), (5+8=13), (8+13=21),...    
Now Let's See The Python Code:
# First, we call our Fibonacci function fib, and it takes parameter or argument n.
def fib(n):    # writes Fibonacci series up to n
     
a, b = 0, 1  # a and b are initialized as 1 and 0, respectively
 while b < n:
  
print b,
   a, b = b, a+b

# The above code (a,b = b ,a+b), just, re-initializes the values of a and b, before going back to the while loop to check if b is less than n.

   

How to Write the Fibonacci Sequence code in Python. How to Write the Fibonacci Sequence code in Python. Reviewed by Unknown on 08:58 Rating: 5

No comments:

Powered by Blogger.