In this article, you’ll learn to write a python program to print the Fibonacci sequence, along with that you’ll also see the algorithm to print the Fibonacci sequence in python.

So, Let’s dive right in!

Hey! Wait, wait…

Before diving into our main concern (i.e., how to write a python program to print the Fibonacci sequence), I’ve a question for you.

Do you know what is the Fibonacci sequence?

If Yes, click here to directly jump over the code which shows you how to print the Fibonacci sequence in Python.

If don’t, Let’s have a quick look on it…

Now, Look at the following sequence of numbers**:**

`F`

= 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, … _{n}

Did you find some pattern or logic in the above sequence?

If Yes! you are so smart. ☺️

If No, Let me tell.

First of all, as we can see that the name of the sequence is `F`

, which is simply the short form of Fibonacci numbers here. Where _{n}`n`

is the subscript to `F`

.

You can give any name to your sequence, for simplicity and for any user or reader to easily recognize it so that they can easily figure out the purpose of the sequence, that’s why I’ve given the name of the sequence is `F`

here._{n}

And, If you observe the above sequence carefully, you’ll find the following**:**

- The list contains infinite number of elements (terms), as you can see that the list is not ending at any specific number or at any specific position. It’s just going on and on and on…
- The sequence only contains
*whole numbers**(numbers without fractions, decimals and negative integers)*. - The first term of this sequence is
`0`

and the second term is`1`

. - Each term in the above sequence is the sum of two numbers before it, or you can say that each number of the sequence is obtained by adding the two preceding (previous) numbers.

So, after combining all the above statements together we can say that,

**–** A Fibonacci sequence is an infinite sequence of whole numbers in which each number in the sequence is obtained by adding the two preceding numbers.

Fibonacci sequence generally starts from `0`

, and `1`

. Which means, by default the first two numbers of the sequence will be `0`

, and `1`

.

Mathematically, It can be defined as follows**:**

`F`

, _{0} = 0`F`

_{1} = 1

And,

`F`

_{n}`=`

`F`

_{n-1}`+`

`F`

{for n>1}_{n-2}

Where, `F`

is the first term, _{0}`F`

is the second term, _{1}`F`

is the nth term, _{n}`F`

is the _{n-1}`(n-1)`

term and ^{th}`F`

is the _{n-2}`(n-2)`

term of the sequence.^{th}

**Example:**

- The third number in the above sequence is
`1`

, which is obtained by adding the two numbers before it { i.e.,`(0+1)`

}. - The fourth number in the sequence is
`2`

, which is obtained by adding the two numbers before it { i.e.,`(1+1)`

} and so on…

In some other definitions, the value `F`

is omitted, so that the sequence starts with _{0}`F1`

`=`

`F2`

`=`

`1`

And, `F`

_{n}`=`

`F`

_{n-1}`+`

`F`

{It is valid for n>2}_{n-2}

### Algorithm for printing Fibonacci sequence:

**Step 01:**Start**Step 02:**[Define a*function*using the`def`

keyword and pass a*parameter**(argument)*inside the parentheses of the function. ]- Let’s say the name of the function is
`fib`

and the parameter is`n`

, ‘n’ denotes the input value given by the user uptill which the user wants to generate the Fibonacci sequence. So, function definition would be like**:**def`fib(n)`

.

- Let’s say the name of the function is
**Step 03:**[Initialize two variables. ] Let’s say the two variables are`a`

and`b`

, and we are initializing it as**:**`a = 0`

and`b = 1`

**Step 04:**Check a statement using the`if`

keyword, If ‘**n**‘ value is less than or equal to`0`

, Print “invalid input”**Step 05:**Elif ‘**n**‘ is equal to`1`

, Print the value of ‘**a**‘**Step 06:**Else, execute the statements from Step`07`

to`12`

**Step 07:**print the value of`a`

, value of`b`

**Step 08:**Repeat Step`09`

to`12`

for`i = 2`

to`i < n`

**Step 09:**Assign the value of`c`

as**:**`c = a + b`

**Step 10:**Assign the value of`a`

as:`a = b`

**Step 11:**Assign the value of`b`

as:`b = c`

**Step 12:**Print the value of ‘**c**‘**Step 13:**Stop

In the above algorithm, Step 01 to step 07 are self explanatory. Right?

So, Let’s move into the next step *i.e., step 08*.

After printing the value of `a`

and `b`

, you’ll get `0`

and `1`

. So, step 07 is done.

Now, If you are thinking I’ll be printing `1`

then `2`

then `3`

then `5`

, we can do that but, then how many numbers I can do that.

Maybe I can do it for top 10 terms, top 50 terms. I mean first 10, first 50 terms and so on…

But, It should be automated. It should be done by computer. Right?

Because, There is no any mean to writing a code if we will do it manually.

So, to execute a statement or a *block of code (group of statements)* in a reapted and in an automatic manner we can use a loop.

So, After printing `0`

and `1`

. I want to print the next, then next after next number and so on…that we should be repeated, and to repeat something there is a loop.

The famous one we all love, which is the `for`

loop.

So, Let’s use `for`

loop here.

In step 08 we are using a `for`

loop to iterate the `for-block`

, Or in other words, we can say that we are using the for loop to iterate the *block of code* *(Group or sequence of statements)* inside the for loop.

So, I’ll say for `i`

in `range(2, n):`

Want to learn more about the `range()`

function?… click here.

`i`

is the counter variable for the `for`

loop here which is ranging from `2`

to `n`

terms, excluding the last term. Means, the for loop will run only upto `(n - 1)`

terms.

Now, you might be wondering that why I’m iterating the loop starting from `2`

and why it only goes till (n – 1). Right?

The answer of the above questions are very straightforward, since I’m printing the first two numbers so we don’t have to start the range from `0`

.

And, as we already know, by default the iteration of a `for`

loop starts from `0`

and continues until we reach the last item in the sequence.

That’s why I’m starting the loop ranging from `2`

because, the `1`

and the ^{st}`2`

number has been already printed.^{nd}

And, as you can see that here we are printing the value of `a`

and the value of `b`

before using the for loop.

And, we can consider the index value of a as `0`

and the index value of b as `1`

by default.

So, to printing the fibonacci sequence from the third position i.e., from index value `2`

we have to start iterating the list of fibonacci sequence from `2`

.

And, the iteration goes till `(n - 1)`

because, as I’ve already discussed above that by default the iteration of a for loop starts from `0`

. So, If we exclude the stop value ( i.e., `n`

) of the range then only we can reach to the exact position uptill where we want to print the fibonacci sequence.

Because, the index value of the first element is `0`

and not `1`

. So, as you can see the index value of `1`

is `0`

which is basically `(1 - 1)`

. so the index value of last element which is n here will be `(n - 1)`

.

After that, as we already know each term of a fibonacci sequence is the sum of the two previous number.

And, we have already printed the first two term of the fibonacci series. So, to print the next upcoming terms from the third we have to add the first two numbers and assign it to an another variable. Let’s say the variable here is `c`

.

Next, we are swaping the two variables ‘a’ and ‘b’.

Now, your question would be why we are swaping ‘a’ and ‘b’. Right?

We are swaping ‘a’ and ‘b’ because, initially when you say `0`

and `1`

i.e., ‘a’ and ‘b’, for the next iteration what if you shift both `a`

and `b`

to one position forward.

What if you shift ‘a’ and ‘b’, now what will happen if the new ‘a’ and ‘b’ will be 1 & 1.

Once you add them then again you have to shift so it will be new ‘a’ and ‘b’ would be 1 and 2 that’s what we want. Right?

So, how do we swap?

It’s very simple, first of all, assign `a`

is equal to `b`

and then assign `b`

is equal to `c`

. So, that’s how we can shift.

Now once we got new values for `a`

and `b`

, we can simply print the value of `c`

.

In the next iteration you will add the values and that will go in `c`

and then this will continued uptill where you want to print the Fibonacci sequence.

So, now let’s move on to the actual implementation of the above algorithm to write the code.

### code:

```
# Writing a python program to print the Fibonacci sequence
def fib(n):
a = 0
b = 1
if n <= 0:
print("Invalid input")
elif n == 1:
print(a)
else:
print("{",a,",", end=" ")
print(b,",", end=" ")
for i in range(2, n):
c = a + b
a = b
b = c
print(c,",", end = " ")
print("...}", end = " ")
```

If you call the `fib(n)`

function with passing some integer parameter `n`

to it, then it will give the following output**:**

**Output:**

```
# for values less than 0
fib(-4)
Invalid input
# for value equal to 1
fib(1)
0
# for values greater than 1
fib(7)
{ 0 , 1 , 1 , 2 , 3 , 5 , 8 , ...}
```

## Conclusion:

In this article, you learned how to write a program to print the Fibonacci sequence in Python, along with that you also became familiar with the algorithm to print the Fibonacci sequence in python.

So,

**I really hope that you liked my article and got a lot of value from it.**

Now, It’s your turn!

If you have any question, feel free to ask in the comment section below right now.

And, and, and…

Don’t forget to share this article to your friends.

Coz, as you know, Sharing is Caring! ?… Right?