wiz-icon
MyQuestionIcon
MyQuestionIcon
1
You visited us 1 times! Enjoying our articles? Unlock Full Access!
Question

Take a look at the series below:
1, 1, 2, 3, 5, 8, 13, 21, 34, 55…
To form the pattern, start by writing 1 and 1. Add them together to get 2. Add the last two numbers: 1 + 2 = 3. Continue adding the previous two numbers to find the next number in the series. These numbers make up the famed Fibonacci sequence: previous two numbers are added to get the immediate new number.

Open in App
Solution

The number of terms of the Fibonacci series can be returned using the program by getting the input from the user about the number of terms to be displayed.
The first two terms will be printed as 1 and 1 and then using ‘for’ loop (n - 2) times, the rest of the values will be printed.
Here, ‘fib’ is the user-defined function which will print the next term by adding the two terms passed to it and then it will return the current term and previous term. The return values are assigned to the variables such that the next two values are now the input terms.

Program:
def fib(x, y):
z = x + y
print(z, end=",")
return y, z

n = int(input("How many numbers in the Fibonacci series do you want to display? "))

x = 1
y = 1

if(n <= 0):
print("Please enter positive numbers only")
elif (n == 1):
print("Fibonacci series up to",n,"terms:")
print(x)
else:
print("Fibonacci series up to",n,"terms:")
print(x, end =",")
print(y, end =",")
for a in range(0, n - 2):
x,y = fib(x, y)

print()

​OUTPUT:
How many numbers in the Fibonacci series do you want to display? 5
Fibonacci series up to 5 terms:
1,1,2,3,5,

flag
Suggest Corrections
thumbs-up
0
Join BYJU'S Learning Program
similar_icon
Related Videos
thumbnail
lock
What is an Equation?
MATHEMATICS
Watch in App
Join BYJU'S Learning Program
CrossIcon