Write a Python program to generate and print the Fibonacci sequence up to a specified number of terms.
Input-Output Examples
plaintext
Example 1:
Input: Enter the number of terms: 5
Output: The Fibonacci sequence is: 0 1 1 2 3
Example 2:
Input: Enter the number of terms: 8
Output: The Fibonacci sequence is: 0 1 1 2 3 5 8 13
Algorithm to print the Fibonacci Series upto N terms
- Start
- Take input: Prompt the user to enter the number of terms.
- Check if the number of terms is valid:
- If the number of terms is less than or equal to 0, display an error message.
- If the number of terms is 1, print only the first term (0).
- If the number of terms is greater than 1, generate the Fibonacci sequence using a loop.
- Print the sequence.
- End
Python Program to print the Fibonacci Series upto N terms
python
# Python program to print the Fibonacci sequence
# Take input from the user for the number of terms
n_terms = int(input("Enter the number of terms: "))
# First two terms of the Fibonacci sequence
n1, n2 = 0, 1
count = 0
# Check if the number of terms is valid
if n_terms <= 0:
print("Please enter a positive integer.")
elif n_terms == 1:
print(f"The Fibonacci sequence up to {n_terms} term is: {n1}")
else:
print(f"The Fibonacci sequence up to {n_terms} terms is:")
while count < n_terms:
print(n1, end=" ")
# Update values for the next term
nth = n1 + n2
n1 = n2
n2 = nth
count += 1
Code Explanation
- Taking input from the user:
The program usesinput()
to take the number of terms from the user. The input is converted to an integer usingint()
. - Checking if the input is valid:
- If the user enters a number less than or equal to 0, the program displays an error message prompting the user to enter a positive integer.
- If the number of terms is 1, the program prints only the first term (0) since the Fibonacci sequence starts with 0.
- Generating the Fibonacci sequence:
For more than one term, the program uses awhile
loop to generate the Fibonacci sequence. It starts with two initial terms:n1 = 0
andn2 = 1
. The loop iterates, printing the current term (n1
) and updating the values ofn1
andn2
by calculating the next term as the sum of the previous two terms (nth = n1 + n2
). - Displaying the sequence:
The Fibonacci sequence is printed one term at a time, separated by spaces. The loop runs until the specified number of terms is printed.