Visit Original Non-AMP Page
Write a program to print the Fibonacci Series in Python [CODE]
In this tutorial we are going to write a program to print the Fibonacci Series in Python.
And here i am about to explain little-bit about Fibonacci Series (if you just need the Python CODE, Scroll Down for that).
What is Fibonacci Series?
Fibonacci Series or Fibonacci Sequence is a number Series where each number is a sum of last two Numbers that precede it.
In simple language, Fibonacci Series contains number, where each number is the sum of last two digits that come before it.
For Example: 0, 1, 1, 2, 3, 5, 8.
num1 = 0 num2 = 1 myFibonacciNumber = 5 loop = 0 sum while loop<myFibonacciNumber: print(num1) sum = num1 + num2 num1 = num2 num2 = sum loop += 1
Variables used in this Example
We are declaring 5 Variable to store different Values.
Variable num1 for storing the First Integer,
Variable num2 for storing the Second Integer,
Variable myFibonacciNumber for storing the Fibonacci Number (You can think of it like a Fibonacci Limit),
Variable loop for storing the loop number (where we will run loop from 0 to given Fibonacci Number. For example 0 to 5).
and the last Variable sum for storing the sum/total number.
While loop for Fibonacci number in Python
In the example we are using while loop for running a looping through 0 to 5(where 5 is our Fibonacci number).
Where we will print the num1 variable (by using print(num1)).
After printing the first Digit, we will store the sum of num1 (first Digit) and num2 (second digit) inside the Variable sum (by using sum = num1 + num2).
Now we need to swap the values, Where first we will swap Variable num2 value in Variable num1 (by using num1 = num2).
After that we will Swap the Sum/Total in Variable num2 (by using num2 = sum)
[First Swap num1 = num2 second Value became the First Value and Second Swap num2 = sum Sum/Total value became the Second Value for the NEXT LOOP.]
Now lets increment the loop number/counter (by using loop += 1).
So by incrementing the Variable loop value we are adding 1 on every loop run.
Final Output
num1 = 0 num2 = 1 myFibonacciNumber = 5 loop = 0 sum while loop<myFibonacciNumber: print(num1) sum = num1 + num2 num1 = num2 num2 = sum loop += 1
After Declaring the Variable, Creating a While loop, Printing the First Value, Storing the Total in Variable sum, Swapping the Variable num2 with Variable num1, Swapping the the Sum/Total with Variable num2 and Incrementing the Loop Variable.
You will get the Fibonacci Series as a Result.