Python: Fibonacci sequence

 Fibonacci sequence:

Here we will look, that how to find the Fibonacci series/ Fibonacci sequence is  for certain given number.

1- Below line will take input from console. For type conversion we have placed "int" at starting point. so that it will store an integer number in "getNumFromConsole" variable.

getNumFromConsole = int(input("Enter the value of 'n': "))
 
If "int" is removed from above line then it will take string only.

After that we have taken some variables and assign some initial values. these initial values will be use in use when first iteration of loop will be executed. 
 

in below code under loop, we have just swapped the values of variable a and b. when first iteration of loop will execute, then all initial value will be in use and calculate the sum.

when second iteration of loop will execute, then sum will print and last stored value of b moved to variable a and value of sum will move to variable b, after that sum will be calculated as per the assign value.

 while(count < getNumFromConsole):
    print(sum)
    count = count + 1                    #increment loop count
    a = b
    b = sum
    sum = a + b 

 

Below table shows loop iteration how swapping of value is getting placed at every loop iteration.




Print SumVariable a Variable bVariable sum = a+bLoop_Iteration
0 0 1 1 Loop_1st Iteration All initial value is taken
1 0 1 1 Loop_2nd Iteration
1 1 1 2 Loop_3th  Iteration
2 1 2 3 Loop_4th  Iteration
3 2 3 5 Loop_5th  Iteration
5 3 5 8 Loop_6th  Iteration
8 5 8 13 Loop_7th  Iteration
13 8 13 21 Loop_8th  Iteration
21 13 21 34 Loop_9th  Iteration
34 21 34 55 Loop_10th  Iteration

 
 
 
Code:
============================


# python/bin/ 

getNumFromConsole = int(input("Enter the value of 'n': "))

a = 0                 #First variable 

b = 1                 #Second variable 

sum = 0 

count = 0                     #For the use of loop initial point. 

print("Fibonacci Series: ") 

while(count < getNumFromConsole):
    print(sum)
    count = count + 1                    #increment loop count
    a = b
    b = sum
    sum = a + b

==========================

Result:

Enter the value of 'n': 10


0

1

1

2

3

5

8

13

21

34

No comments:

Post a Comment