Progress

# Python program to print Fibonacci Sequence Problem Statement: Write a Python program to print the Fibonacci sequence up to n terms.

Description: The Fibonacci sequence of numbers 0, 1, 1, 2, 3, 5, 8, 13, 21, 34 … formed by adding its previous two numbers.

It is defined by Fn = Fn-1+Fn-2.

Example:

``````Input: 7
Output: 0 1 1 2 3 5 8
Explanation: 0 and 1 are first two numbers in fibonacci sequence. Then next terms are calculated by
0+1=1
1+1=2
1+2=3
2+3=5
3+5=8
.
.
.``````

Hint: Initialize two variables with initial Fibonacci sequence 0 and 1. Then use for loop to print and add them for the next sequence.

Now you have the logic, you should try to write a Python program to find and print Fibonacci sequence up to n terms.

## Python Program: Find Fibonacci Sequence using loop

fibonacci.py
Copy
``````n =abs(int(input("How many fibonacci numbers you want: ")))
fib1 = 0
fib2 = 1
while(n>0):
print(fib1)
nextTerm = fib1+fib2
fib1 = fib2
fib2 = nextTerm
n-=1``````
Output
```How many fibonacci numbers you want: 5
0
1
1
2
3```

At first, we take the input in string form and convert to integer followed by calculating absolute value using `abs()` function.

As described in the logic the first two Fibonacci numbers are 0 and 1.

Then we use while loop to print the Fibonacci number and find the next term using the formula.

While loop runs n times as entered by the user, printing n Fibonacci numbers.

Share the Post ;)

Related Posts