# How to Generate Fibonacci Sequence In Python

We will soon start posting our python tutorials, but before doing that I would like to show you how beautiful and powerful python is. In this article I will share a simple script that can be used to generate fibonacci 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.

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 name_of_script.py**.

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 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.

### You might also like

**Filed Under :** HOWTOS, PROGRAMMING