Python Program for Fibonacci Series
In this tutorial, we will discuss a python program for how to generate the Fibonacci series up to a given number of terms.
Before going to the program first, let us understand what is a Fibonacci Series.
Fibonacci Series:
- The Fibonacci series is a sequence of numbers where each number is the sum of the two preceding ones, usually starting with 0 and 1.
- For example, the first few terms of the Fibonacci series are 0, 1, 1, 2, 3, 5, 8, etc.
Related: Python program to find factorial of a number
Program code for the Fibonacci series in Python
# Fibonacci Series Program in Python def fibonacci(n): fib_series = [0, 1] for i in range(2, n): next_term = fib_series[-1] + fib_series[-2] fib_series.append(next_term) return fib_series terms = int(input("Enter the number of terms: ")) print(f"The first {terms} terms of the Fibonacci series are: {fibonacci(terms)}")
Explanation
- Function Definition: The
fibonacci
function takes an integern
as input and returns a list containing the firstn
terms of the Fibonacci series. - Initialize Series: The function initializes the series with the first two terms, 0 and 1.
- Generate Series: It then generates the remaining terms by iterating and summing the last two terms of the series.
- Main Program: The program prompts the user to enter the number of terms and then generates the Fibonacci series using the
fibonacci
function.
Output
- When you run the above program, it will prompt you to enter the number of terms.
- After entering the number, it will generate the Fibonacci series up to that number of terms and print the result.
Conclusion
- In this tutorial, we learned how to generate the Fibonacci series up to a given number of terms using a Python program.
- Understanding this concept is essential for solving various mathematical problems and competitive programming challenges.
- Practice this example to enhance your programming skills and understanding of the Fibonacci series.