In this Python lesson, we will practice how to write a program to create the Fibonacci sequence. The Fibonacci sequence is a sequence of integer numbers where the first two numbers are 0 and 1 respectively and the next term is the sum of the previous two numbers. The Fibonacci sequence is shown below.
0, 1, 1, 2, 3, 5, 8, 13, 21, …
Example: Find Fibonacci Sequence
# request nth term from user
nt_num = int(input('Enter nth term: '))
# first two terms
n1, n2 = 0, 1
count = 0
# check if the number of terms is valid
if nt_num <= 0:
print('Enter only positive number')
# if there is only one term, return n1
elif nt_num == 1:
print('Fibonacci sequence of {0} = {1}'.format(nt_num,n1))
# generate fibonacci sequence
else:
print('Fibonacci sequence:')
while count < nt_num:
print(n1)
nth = n1 + n2
# update values
n1 = n2
n2 = nth
count += 1
Output
Enter nth term: 8
Fibonacci sequence:
0
1
1
2
3
5
8
13
In the program above, we stored the user input in the nt-num. And we initialize the first and second terms to 0 and 1 respectively. If the number of terms is more than 2, we use a while loop to find the next term in the sequence by adding the preceding two terms.