Python Program to Generate the Fibonacci sequence
In this example, we will write a simple program to take input number from the user and display the Fibonacci sequence up to n terms. To better understand this example, make sure you have knowledge of the following tutorials:-
Fn = Fn-1 + Fn-2 with seed values F0 = 0 and F1 = 1.
E.g. 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, ……..
Python Program to Generate the Fibonacci sequence
no_terms = int(input("How many terms for the Fibonacci sequence?: ")) # Seed values for the sequence n1 = 0 n2 = 1 count = 0 if no_terms <= 0: print("Please enter a positive integer") elif no_terms == 1: print("Fibonacci sequence up to", no_terms, ":") print(n1) else: print("Fibonacci sequence up to", no_terms, ":") while count < no_terms: print(n1, end=' ') nth = n1 + n2 n1 = n2 n2 = nth count += 1
The output of the above program is:-
Fibonacci sequence up to 10 :
0 1 1 2 3 5 8 13 21 34
Program Explanation
The user provides the input for the number of items to generate in the Fibonacci series. Next, the initialization process takes place for seed value for 2 variables, n1, and n2 with n1=0 and n2=1. A counter count maintains the track of the generation of the series up to n terms. The negative number is not taken into account with the first condition in the if statement. A while loop keeps the sum of the first two terms and proceeds the series by interchanging the variables.