Python program that prints the Fibonacci sequence of a given number of terms:

Created with Sketch.

Python program that prints the Fibonacci sequence of a given number of terms:

terms = int(input("Enter the number of terms: "))

# Initialize the first two terms
first_term = 0
second_term = 1

# Check if the number of terms is valid
if terms <= 0:
    print("Please enter a positive integer")
elif terms == 1:
    print("The Fibonacci sequence upto",terms,":")
    print(first_term)
else:
    print("The Fibonacci sequence upto",terms,":")
    print(first_term, ",", second_term, end=", ")
    for i in range(2, terms):
        next_term = first_term + second_term
        print(next_term, end=", ")
        first_term = second_term
        second_term = next_term

The program prompts the user to enter the number of terms using the input() function, and stores the value in the variable “terms”. It then uses an if-elif-else statement to check if the number of terms is valid, then initializes the first two terms of the Fibonacci sequence which are 0 and 1. Then, it uses a for loop to calculate and print the next terms of the Fibonacci sequence by adding

Leave a Reply

Your email address will not be published. Required fields are marked *