Python Program : Generate a Fibonacci Sequence Using While

In this sample program, you will learn how to generate a Fibonacci sequence in Python and show it using the print() function.

To understand this demo program, you should have the basic Python programming knowledge and should know about the following topics:

We’ll use both the above constructs to form the Fibonacci sequence in the sample given below. This series is a list of integer numbers as shown here.

0, 1, 1, 2, 3, 5, 8...

The above sequence starts with the two pre-defined numbers 0 and 1. Remaining other values get generated by adding the preceding two digits appearing in the list.

It means if you wish to know the value at the index X, then it would be the sum of values at the (X-1) and (X-2) positions.

Generate a Fibonacci sequence in Python

In the below program, we are using two numbers X and Y to store the values for the first two elements (0 and 1) of the Fibonacci sequence.

After that, there is a while loop to generate the next elements of the list. It is doing the sum of two preceding items to produce the new one.

There is a swapping operation in the next line to continue the while loop until the last element of the sequence gets printed.

# Program to generate the Fibonacci sequence in Python

# The length of our Fibonacci sequence
length = 10

# The first two values
x = 0
y = 1
iteration = 0

# Condition to check if the length has a valid input
if length <= 0:
   print("Please provide a number greater than zero")
elif length == 1:
   print("This Fibonacci sequence has {} element".format(length), ":")
   print("This Fibonacci sequence has {} elements".format(length), ":")
   while iteration < length:
       print(x, end=', ')
       z = x + y
       # Modify values
       x = y
       y = z
       iteration += 1

There could be three possible outputs of the above code.

The length of the sequence is 0 or less than zero.

Please provide a number greater than zero

The sequence contains a single element.

This Fibonacci sequence has 1 element :

The sequence contains multiple elements.

This Fibonacci sequence has 10 elements :
0, 1, 1, 2, 3, 5, 8, 13, 21, 34,

You can further play with the program by supplying different values for the length variable.