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,