Fibonacci Series in Python Using While Loop

In today’s lesson, we are going to learn a Python Program to Find the Fibonacci series in python using while loop.

What is the Fibonacci series in Python?

In Python, the Fibonacci series is a sequence of numbers in which each number is the sum of the two preceding ones, often beginning with 0 and 1. It is described mathematically by the recurrence relation F(n) = F(n-1) + F(n-2) with F(0) = 0 and F(1) = 1.

The Fibonacci series can be created in Python using a variety of approaches such as recursion, iteration, or memoization. One frequent way is to iteratively calculate and store the Fibonacci numbers using a loop. Because of its intriguing mathematical features and self-replicating patterns, this series has applications in many domains, including mathematics, computer science, and nature, and it frequently arises in algorithms, number theory, and dynamic programming issues.

Fibonacci Series in Python Using While Loop – Code

# Find Fibonacci Series in Python Using While Loop
# we are taking a number from user as input

# entered value will be converted to int from string
n = int(input("Number of Fibonacci Series to be Printed: "))

# print initial 2 number to start fibonacci series
a, b = 0, 1
print(a, b, end=' ')

i = 0
while (i < n-2):
    c = a + b
    # add the last two numbers and print
    print(c, end=' ')
    a = b
    b = c
    i = i + 1
  • Input from the user
    • As the Fibonacci series is a non terminating series, we ask the user to enter the number, which will be the length of the Fibonacci series to be printed
    • As we asking the user to enter a number, we use the int() function to convert the user’s input into an integer and stored as ‘n’
    • Syntax : n = int(input(“Number of Fibonacci Series to be Printed: “))
  • Initiating the Series
    • As we know that the first 2 digits of the Fibonacci Series is 0 and 1, we are going to assign them a variable ‘a’ and ‘b’  respectively
    • These value are then printed using the print() function with ‘end=’ ‘’ to ensure the value are printed on the same line
  • Initiating the While loop
    • As we need multiple iteration of the same operation, we are using the while loop to perform this action
    • We are using variable ‘i’ to keep track of the number of iterations
    • The ‘while’ loop is run for ‘n-2’ times, as the first two digits are defined already
    • Inside the loop, the next number in the sequence is calculated as the sum of the previous two numbers, ‘a’ and ‘b’. This value is stored in the variable ‘c’
    • The ‘print()’ function is used to print ‘c’ on the same line as the previous values separated by a space
  • Iteration and Termination of the While Loop
    • The values of ‘a’ and ‘b’ are updated for the next iteration
    • With ‘a’ set to the previous value of ‘b’
    • And ‘b’ being the previous value of ‘c’
    • Finally, the loop counter ‘i’ is raised by 1, and the loop continues till the counter reached ‘n-2’

The code exists giving out the sequence in a line 

Output:

Number of Fibonacci Series to be Printed: 10
0 1 1 2 3 5 8 13 21 34

In this program, we generated the Fibonacci series in python using while loop. When the user enters the number of terms of the series to be printed, say ‘n’. The code outputs the first two terms in the series, which are initialised as 0 and 1, respectively. Then it starts a while loop, which runs until it prints the ‘n-2′ number of terms. Within the loop, the program adds the series’ last two values (a and b) to get the next term (c), which is then printed. 

The values of ‘a’ and ‘b’ are shifted to the right by one position, making ‘b’ the current term and ‘a’ the previous term, and the loop continues like before.

The output of the Fibonacci series in python using while loop, when the user enters ’10’ is 0, 1, 1, 2, 3, 5, 8, 13, 21, 34.

Why do we use the While loop to find the Fibonacci series

Apart from the above method, you can also find the Fibonacci series using recursion or for loop in Python. If the size of the input is large, using recursion can lead to excessive stack usage and slow execution time but, for small input values, recursion can be an elegant and concise solution. When we use a while loop, as shown above, the coding is simple and efficiently generates the series. 

Real-life applications of the Fibonacci Series in Python Using While Loop

The Fibonacci series has several real-life applications in various fields, and implementing it in Python using a while loop demonstrates the power of iterative programming. Here are some specific real-world applications of the Fibonacci sequence, particularly when implemented through Python’s while loop:

1. Algorithm Optimization and Dynamic Programming

  • Fibonacci numbers help in understanding optimal substructure and overlapping subproblems in dynamic programming, such as calculating Fibonacci efficiently without recursion to avoid stack overflow.
  • Examples include using it for memoization in competitive coding and system optimization.

2. Stock Market Analysis

  • Fibonacci numbers are used to predict future stock price levels through Fibonacci retracement. Analysts use the sequence to identify potential support and resistance levels for asset prices.

3. Data Structures and Tree Algorithms

  • Fibonacci numbers are applied in building Fibonacci heaps, which are advanced data structures used in graph algorithms (like Dijkstra’s). The series also helps analyze the structure of binary trees and AVL trees.

4. Computer Graphics and Simulations

  • Fibonacci spirals appear in nature and are modeled in computer graphics to simulate natural phenomena, such as shells or galaxies. While loops are often used to generate sequences to mimic these patterns efficiently.

5. Biological Systems and Population Modeling

Fibonacci sequences are observed in modeling the population growth of organisms or even the flowering of plants. Using Python’s while loop, biologists simulate such patterns for research on animal reproduction and crop yields.

In conclusion, the Fibonacci series offers valuable insights and applications in areas such as stock market predictions, biological modeling, and data structures. Implementing the Fibonacci series in Python using while loop is a simple yet powerful way to explore this concept and enhance algorithmic thinking.

For more coding tutorials and practical insights, visit Newtum, where we provide essential programming techniques to accelerate your learning and coding journey.

FAQs for Fibonacci series in python using while loop

Can I modify the above code to print the Fibonacci series in reverse order?

Yes, you can modify the code by changing the initial values of ‘a’ and ‘b’ to the last two numbers of the series., Then apply a decrementing loop variable ‘i’ instead of incrementing it.

How can I optimize the above code to use fewer variables?

You can use a single variable to store the sum of the last two numbers instead of ‘c’. This will reduce the number of variables used in the code.

Can I generate the Fibonacci series starting from any two given numbers?

Yes, you can modify the code by changing the initial values of ‘a’ and ‘b’ to the desired numbers.

What will happen if I enter a negative number for the number of terms in the Fibonacci series?

The code will result in an error message. However, you can add a check at the beginning of the code to ensure that the input value is non-negative.

What are some real-world applications of the Fibonacci series?

The Fibonacci series has applications in many fields, including finance, computer science, and nature. It can be used to model population growth, stock market trends, and the growth of plants.

About The Author

Leave a Reply