Python Program to Print the Fibonacci sequence


10xer.co Ad Sponsored

ⓘ Sponsored by 10xer.co

The Fibonacci sequence is a series of numbers in which each number is the sum of the two preceding numbers. The sequence starts with 0 and 1, and the next number in the sequence is obtained by adding the previous two numbers. So the first few terms of the sequence are:

0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, …

The Fibonacci sequence is named after the Italian mathematician Leonardo Fibonacci,


Python Code :

The below Python program prints the Fibonacci sequence up to a given number of terms:


# Get input from user
num_terms = int(input("Enter the number of terms: "))

# Initialize variables
n1, n2 = 0, 1
count = 0

# Check if the number of terms is valid
if num_terms <= 0:
    print("Please enter a positive integer")
elif num_terms == 1:
    print("Fibonacci sequence up to", num_terms, "term:")
    print(n1)
else:
    print("Fibonacci sequence up to", num_terms, "terms:")
    while count < num_terms:
        print(n1)
        nth = n1 + n2
        n1 = n2
        n2 = nth
        count += 1

In this program, the user is prompted to enter the number of terms of the Fibonacci sequence they want to print. The program then prints the Fibonacci sequence up to that number of terms using a while loop.

The Fibonacci sequence is a series of numbers in which each number is the sum of the two preceding numbers. For example, the first 10 terms of the Fibonacci sequence are: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34.

To print the Fibonacci sequence, the program initializes two variables n1 and n2 to 0 and 1, respectively. The program also initializes a variable count to 0. If the user enters a non-positive number of terms, the program prints out a message asking the user to enter a positive integer. If the user enters 1, the program prints out 0 as the only term of the sequence. Otherwise, the program uses a while loop to print out the Fibonacci sequence up to the desired number of terms. The loop prints out the current value of n1.

For example :


Enter the number of terms: 10
Fibonacci sequence up to 10 terms:
0
1
1
2
3
5
8
13
21
34


10xer.co Ad Sponsored

ⓘ Sponsored by 10xer.co