write the Python coding to generate Fibonacci series for n terms using while loop
Answers
Fibonacci series
n= int ( input ( " enter the limit "))
a= 0
b=1
print (a)
print (b)
m = n - 2
while ( m >0 ):
______ c = a + b
______ print (c)
______ a = b
______ b = c
Dry Run
- suppose you enter the value on n = 6
- a = 0
- b =1
- print statement will print 0 and 1
- m = 4 (m= n -2 means 6-2 = 4 )
- in loop 4 > 0
- c = 1 ( c= a + b means 0 + 1 = 1)
- now it will print 1
- a = 1 ( a= b means value of b in a as b =1 )
- b = 1 ( b = c means value of c in b as c = 1 )
- again in loop 3 > 0
- c = 2 ( c= a + b means 1 + 1 = 2)
- now it will print 2
- a = 1 ( a= b means value of b in a as b =1 )
- b = 2 ( b = c means value of c in b as c = 2 )
- 3rd time in loop 2 > 0
- c = 3 ( c= a + b means 1 + 2 = 3)
- now it will print 3
- a = 2 ( a= b means value of b in a as b =2 )
- b = 3 ( b = c means value of c in b as c = 3 )
- 4th time in loop 1 > 0
- c = 5 ( c= a + b means 2 + 3 = 5)
- now it will print 5
- a = 3 ( a= b means value of b in a as b =3 )
- b = 5 ( b = c means value of c in b as c = 5 )
- 5th time in loop 0>0 condition false out from loop
☆ output will be --> 0 1 1 2 3 5
note : imagine it ( ______) invisible. I am using it for indentation
In the finonacci series, the starting numbers are always 1 and 1.
To continue making the code, we will first have a list with 1 and 1 and then write the code to get our desired output.
series = [0,1,1]
Now, we know that in the fibonacci series, the next is determined by the sum of the previous two numbers.
Now, with this on our heads, lets determine the next number. The number after 1,1. The number would be the sum of these both numbers. Hence, it is going to be 2. We now have 1,1,2. What is the next number? It is the sum of 2 and 1 and it is 3.
Now that we have the main idea, allow me to put this in the python form. We know that the next number is determined by the sum of the previous 2 numbers. But remember, before we determine the next number, we know that we will have to add up the last and the second last number in the list.
If we have series = [0,1,1,2,3,5]
The next number is the sum of the last(5) and the second last(3) number. Which is 8.
In python, how do we know the last and the second last. For the last, we use the index -1 and for the second last we use the index -2.
Remember, we will have to have a limit for the series. For that, we will be using the while loop and the len() command so that the length of the elements in the list don't exceed the limit.
limit = int(input('Enter your limit:'))
while len(series) < limit:
series.append(series[-1] + series[-2])
That is it. Now, all we have to do is print this! :)