[Python] Fibonacci Sequence
One one two, three five eight
Sounds so simple, nothing great
Thirteen, twenty-one, thirty-four
The hinges creak on an opening door
A repeating patter of the masters hand
Signing his work, the universal plan
Learn to look, the pattern’s plain to see
In the smile you flash, the dance of the honeybee
In the spirals of the pine cone and little acorn cap
Spiral arm galaxies and the ocean’s wave whitecap
In the swirl of the seashell, the air vortex of a wing
The hurricane’s eye and a thousand unseen things
Welcome to the mystery of the Greek letter phi
The measurement of beauty to the human eye
The golden ratio, one point six one eight
One, One, Two; Three, Five Eight
It is actually very hard not to be familiar with the Fibonacci sequence. But we are not really going to go into details about its history and all, we just want to write a code in Python which can produce the Fibonacci sequence up to the (user provided) N-th element. However, if you need to know more about the sequence, there are useful links at the end of the post.
Ok then, just to know what we are going to generate, we need a quick look at the Fibonacci sequence:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89 ….
Basically, the first three elements are 0, 1 and 1 and after that every element in the sequence is the sum of the two previous numbers.
So, let’s have a quick look at the code:
Running this code and setting N equal to 10, the output will be:
So far so good. Now let’s just quickly review what we have done here:
1. First we ask the user to provide us with a number, and then we store it in a variable called N.
2. We run a quick if-condition to check if the number given by the user makes sense, since the Fibonacci sequence is meaningless for non-positive numbers. Bear in mind that I have used another input function for the case that the initial input by the user was wrong.
3. In the next two steps I create the first three terms of the sequence, and I also create a list so that we can later add the new elements to. Keep in mind that instead of this one could have just easily tried, for instance, Fibonaaci = [0,1,1]
4. Then we use a for loop to calculate the next terms of the Fibonacci sequence, starting from element 3. Each new element is simply the sum of two previous elements. Then we add each new term to the list that we have already created in the previous step.
5. Now, and as a final step, all we have to do is to print the results in a suitable manner. I ran another loop to go through every element of the Fibonacci list, and print the element number along with its value. To combine text and numbers in a print statement, I have changed the type of the numbers to string.
Or you can just, for example, create a simple function to do the same work, in a less stylized way, for you. Consider the following code:
The output of this code for n = 10 would be:
Also watch about the Fibonacci Sequence