In this example, you will learn to print Fibonacci sequence with example.
The Fibonacci sequence is a sequence where the next term is the sum of the previous two terms. The first two terms of the Fibonacci sequence are 0 followed by 1.
The Fibonacci sequence: 0, 1, 1, 2, 3, 5, 8,..., n
Example :
# Program to display the Fibonacci sequence up to n-th term
length = int(input("Enter Length :: "))
# first two terms
n1, n2 = 0, 1
count = 0
# check if the number of length is positive or not
if length <= 0:
print("Please enter a positive integer")
elif length == 1:
print("Fibonacci sequence up to ",length,":")
print(n1)
else:
print("Fibonacci sequence:")
while count < length:
print(n1)
nth = n1 + n2
# update values
n1 = n2
n2 = nth
count += 1
Output :
Enter Length :: 10
Fibonacci sequence:
0
1
1
2
3
5
8
13
21
34
Explanation :
This program will ask user to inputted a number and checks number is positive or not. if number is 1 then it simply prints first element of sequence otherwise it will loop till user inputted number.
Ask anything about this examples