In this tutorial, you will learn how to create a Python program to print the Fibonacci series with an example and a detailed explanation.
Python Program to Print Fibonacci Series Example
n_series = int(input("How many series? ")) n1, n2 = 0, 1 count = 0 if n_series <= 0: print("Please key-in a positive integer") elif n_series == 1: print("Fibonacci series upto",n_series,":") print(n1) else: print("Fibonacci series:") while count < n_series: print(n1) nth = n1 + n2 n1 = n2 n2 = nth count += 1
Explanation
- The code starts by asking the user how many series they want to calculate.
- If there are less than 10, then it will print a message saying "Please key in a positive integer."
- Otherwise, if there is one series or more, it will print out the Fibonacci numbers up to that number of Fibonacci numbers.
- The code starts by declaring two variables:
n1
andn2
. - These are used for counting in each iteration of the loop.
- The variable count is used for keeping track of how many iterations have been done so far and what value has been calculated so far.
- The code is an example of how to create a Fibonacci series.
- The code starts by asking the user for the number of series they would like to create.
- If the user enters a value less than 0, then it will print "Please key in a positive integer."
- Â If the user enters 1, then it will print "Fibonacci series upto" followed by the inputted number and then prints
n1
. - Â The code continues until the count reaches
n_series
.
Output
The output of the above Python Fibonacci program would be as shown below:
How many series? 6
Fibonacci series:
0
1
1
2
3
5
I hope this tutorial helped you understand the Python program to print the Fibonacci series for a given number.
Read also:
- How to Split an Integer into Digits in Python?
- Remove all items from a Queue in Python
- Convert NaN to 0 in Python