Python Program - Print the Fibonacci sequence

www.igif‮oc.aedit‬m

here's a Python program that prints the Fibonacci sequence up to a given number using a loop:

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

# initialize the first two terms
num1 = 0
num2 = 1

# check if the number of terms is valid
if n <= 0:
    print("Please enter a positive integer")
elif n == 1:
    print("Fibonacci sequence:")
    print(num1)
else:
    print("Fibonacci sequence:")
    count = 0
    while count < n:
        print(num1)
        nth = num1 + num2
        # update values of num1 and num2
        num1 = num2
        num2 = nth
        count += 1

In this program, we first use the input() function to get the number of terms in the sequence that the user wants to display, and store it in the variable n.

We then initialize the first two terms of the sequence to 0 and 1, respectively.

Next, we check if the number of terms is valid. If it's not a positive integer, we print an error message. If it's equal to 1, we print the first term of the sequence. Otherwise, we use a while loop to iterate over the range of n, and for each iteration, we print the current term of the sequence (which is equal to num1), update the values of num1 and num2 to get the next term in the sequence, and increment a counter variable count.

Finally, we print out the entire Fibonacci sequence up to the nth term.