Fibonacci Series Program in Python using Iteration

 


1. Program Code:


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

Popular posts from this blog

Pseudocode to Check, Number is Odd or Even

How to Create Marksheet in C