Google News
logo
Python Program to Print the Fibonacci sequence
Here's a Python program to print the Fibonacci sequence up to a given number of terms :
Program :
n = int(input("Enter the number of terms: "))

# initialize the first two terms of the sequence
a, b = 0, 1

# check if the number of terms is valid
if n <= 0:
    print("Please enter a positive integer")
elif n == 1:
    print("Fibonacci sequence up to", n, "term:")
    print(a)
else:
    print("Fibonacci sequence up to", n, "terms:")
    for i in range(n):
        print(a, end=' ')
        c = a + b
        a = b
        b = c
Output :
Enter the number of terms: 15
Fibonacci sequence up to 15 terms:
> 15
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 15
In this program, we first ask the user to input the number of terms they want to print. We then initialize the first two terms of the sequence as `0` and `1`.

Next, we check if the number of terms entered by the user is valid. If the number is less than or equal to zero, we prompt the user to enter a positive integer. If the number is one, we simply print the first term of the sequence, which is `0`.

Finally, if the number of terms is greater than one, we enter a loop and print the first `n` terms of the Fibonacci sequence by adding the previous two terms.