The Fibonacci series is one of the most famous mathematical sequences. In this series, each number is the sum of the two preceding ones, starting from 0 and 1. Python offers multiple ways to generate Fibonacci numbers, and in this article, we’ll explore two methods to print the Fibonacci series: using a while loop and recursion. Whether you’re a beginner or intermediate Python programmer, understanding how to generate Fibonacci numbers is a great way to practice looping and recursion.
The Fibonacci sequence starts with 0 and 1, and each subsequent number is the sum of the two preceding ones. For example:
Before we dive into the code, ensure that you’re comfortable with:
In this approach, we will use a while loop to calculate and print the Fibonacci series up to a given number of terms (denoted as ‘n’).
n
up to which the Fibonacci series should be generated.a = 0
, b = 1
, sum = 0
, and count = 1
.count
is less than or equal to n
:sum
.sum
by adding a
and b
.a
and b
for the next iteration.count > n
is met.Sample Input and Output:
Input:
Output:
Recursion is another powerful method in Python. In this approach, we will define a recursive function to calculate Fibonacci numbers. The function will call itself to compute each number in the series.
n
is 0, return 0. If n
is 1, return 1.n
, return the sum of the Fibonacci numbers at positions n-1
and n-2
.Sample Input and Output:
Input:
Output:
In this article, we explored two methods for generating the Fibonacci series in Python:
Both methods are useful depending on the context of the problem you’re trying to solve. By practicing these techniques, you’ll deepen your understanding of loops and recursion in Python, which are crucial for solving a wide range of problems.
Click Here to Know more our program: