How to Generate Fibonacci Sequence in Python

In this article I will share a simple script that can be used to generate fibonacci sequence numbers. In case you guys don't know the numbers in the following integer sequence: 1,1,2,3,5,8,13,21,34,55,89........... Each new term in the Fibonacci Series is generated by adding the previous two terms.

The following python code can be used to generate Fibonacci sequence. You can also let the user decide how many elements should be included in the sequence but we will cover that in a later tutorial.

#!/usr/bin/python # generate fibonacci sequence in python # fibonacci_numbers = [0,1,1,2,3,5,8,13................] fibonacci_numbers = [0,1] i = 0 j = 1 while len(fibonacci_numbers) <= 13: fibonacci_numbers.append(fibonacci_numbers[i] + fibonacci_numbers[j]) i += 1 j += 1 # fibonacci_numbers = [0,1,1,2,3,5,8.....................] print fibonacci_numbers

The following screenshots show the above script in action.

how to generate fibonacci numbers in python

Open a new terminal(CTRL+ALT+T) and cd to the folder where you have saved the python script for generating fibonacci numbers. To run the script type python

how to generate fibonacci numbers in python

Our simple fibonacci numbers generator program saves the values in a list and prints the list with the elements to the screen. The following picture shows the result.

how to generate fibonacci numbers in python

How Does It Work

  • 1. I crate a list with two elements, 0 and 1.
  • 2. Then I create variables i and j. The script will use them to index the elements of the list.
  • 3. i and j will be incremented by 1. The append method is used to add elements in the fibonacci_numbers list.
  • 4. This continues until the length of the fibonacci_numbers list is less or equal to 13.

I have used a while loop that runs until a defined condition is met. In our case we want the length of the list to be less or equal to 13. while len(fibonacci_numbers) <=13: do this

Note: You can not understand this script if you dont have basic knowledge in the python programming language. I have to add that this is not the best algorithm to generate fibonacci numbers, my intention is to teach you guys to think in your own unique way. I thought it this way and built the script.

Oltjano Terpollari 3:00 am


Your email address will not be published. Required fields are marked *

All comments are subject to moderation.