In this simple python program, we need to generate the Fibonacci series. It's a beginner-level python program.
To understand this example, you should have knowledge of the following Python programming topics:
Fibonacci series is a series of numbers that are calculated by taking the sum of the previous two numbers. For example, to start with zero, the series will be 0, 1, 1, 2, 3, 5 ... we have discussed the Fibonacci series in the previous python program. Here in this python program example, we use recursion to print the Fibonacci series. So we have to know what recursion is in python? Recursion is defined as a function that calls itself directly or indirectly. In this simple python program, we use recursion, which means we call the function itself with a number less than 1 every time until the n is less than or equal to one.
In this beginner python program, we need to accept the number of terms needed in the Fibonacci series and store that value in a variable. Check the num is less than or equal to zero using the
if condition in python, if so display "enter positive integer"
else using a
for loop till the nterms and call the Fibonacci function. inside that function, we check the n is less than or equal to 1. If so, return the number n. Else call the function recursively.
STEP 1: Accept the value of n from the user using the input function in python language and store it in nterms.
STEP 2: Use an if condition to check the nterms less than zero, and if the condition is satisfied, we have to print enter a positive integer.
STEP 3: Use else to print the Fibonacci series.
STEP 4: Use a for loop from 1 to nterms and call the function fibo() and print the result using print in the python programming language.
STEP 1: Check the n, which is the user's parameter is less than or equal to 1.
STEP 2: If so, return the value of n.
STEP 3: Else to call the function with a passing parameter of n-1 and n-2
STEP 4: Return the value of n-1 and n-2 to the python programming language.
def fibo(n): if n <= 1: return n else: return(fibo(n-1) + fibo(n-2)) n = int(input("How many numbers? ")) if n <= 0: print("Please enter a positive integer") else: print("Fibonacci sequence:") for i in range(n): print(fibo(i))
How many terms? 5 Fibonacci Series 0 1 1 2 3