Fibonacci Series Program in Python using Iteration
1. Program Code:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def fibonacci(n): | |
# first two terms of the series | |
a, b = 0, 1 | |
# check if n is 0 or 1 | |
if n == 0: | |
return [] | |
elif n == 1: | |
return [a] | |
# generate the Fibonacci series | |
fib_series = [a, b] | |
for i in range(2, n): | |
c = a + b # compute the next term of the series | |
a, b = b, c # update the values of a and b for the next iteration | |
fib_series.append(c) # add the new term to the list of series terms | |
return fib_series |
2. Program Explanation:
- We define a function called Fibonacci that takes an integer n as input.
- We initialize the first two terms of the Fibonacci series to 0 and 1, respectively, using tuple unpacking: a, b = 0, 1. These values will be updated as we generate the series.
- We check if n is equal to 0 or 1. If n is 0, then we return an empty list because there are no terms in the series. If n is 1, then we return a list with the first term of the series, which is 0.
- If n is greater than 1, then we initialize a list called fib_series with the first two terms of the series, which are 0 and 1.
- We use a for loop to iterate over the range from 2 to n - 1, since we've already accounted for the first two terms of the series.
- Inside the loop, we compute the next term of the series by adding the previous two terms: c = a + b. We then update the values of a and b to prepare for the next iteration: a, b = b, c.
- Finally, we append the new term c to the list of series terms: fib_series.append(c).
- Once the loop is finished, we return the complete Fibonacci series as a list by returning fib_series.
To use this code, you can call the
Fibonacci function with an integer argument n to generate the first n terms of
the Fibonacci series. For example, fibonacci(10) will generate the first ten
terms of the series and return them as a list.
Comments
Post a Comment