def fab(n): if n <= 1: return n else: return fab(n - 1) + fab(n - 2) n = int(input('Enter number of terms: ')) print('Fibonacci sequence:') for i in range(n): print(fab(i))
Output:
Enter number of terms: 5
n = 5
Fibonacci sequence:
0
1
1
2
3
Certainly! The provided Python code defines a function fab
(which should be named fib
for Fibonacci) that recursively calculates the Fibonacci sequence. The code also prompts the user to input the number of terms they want in the sequence and prints the sequence. Here’s a detailed explanation of how the code works:
Explanation
- Function Definition (
def fab(n):
):
- This line defines a function named
fab
that takes one parameter,n
, which represents the position in the Fibonacci sequence.
- Base Case for Recursion (
if(n <= 1):
):
- If
n
is less than or equal to 1, the function returnsn
. This is because the first two terms of the Fibonacci sequence are 0 and 1.
- Recursive Case (
else:
):
- If
n
is greater than 1, the function returns the sum of the previous two Fibonacci numbers (return(fab(n - 1) + fab(n - 2))
). This is the essence of the Fibonacci sequence where each number is the sum of the two preceding ones.
- Input and Output:
- The user is prompted to input the number of terms in the Fibonacci sequence:
python n = int(input('Enter number of terms:'))
- The program then prints “Fibonacci sequence:” as a header for the output.
- A
for
loop iterates from 0 ton - 1
, calling thefab
function for each term and printing the result:python for i in range(n): print(fab(i))
Example
Let’s go through an example where the user inputs a number of terms. Suppose the user inputs the following:
Enter number of terms: 5
The code execution will be as follows:
- Input Number of Terms:
n = 5
- Fibonacci Sequence Calculation:
fab(0)
returns0
fab(1)
returns1
fab(2)
callsfab(1)
andfab(0)
, returns1 + 0 = 1
fab(3)
callsfab(2)
andfab(1)
, returns1 + 1 = 2
fab(4)
callsfab(3)
andfab(2)
, returns2 + 1 = 3
- Output:
Fibonacci sequence: 0 1 1 2 3
Summary
This code defines a recursive function fab
to calculate the Fibonacci sequence. It prompts the user for the number of terms they want and then prints the first n
terms of the Fibonacci sequence. The function fab
uses a straightforward recursive approach to calculate each term, where each number in the sequence is the sum of the two preceding ones.