Python Programs | IT Developer
IT Developer

Python Programs



Share with a Friend

Python Programs - Looping Statements

Generate Fibonacci series up to n terms - Python Program

Example 1 :

# Fibonacci series up to n terms n = int(input("Enter number of terms: ")) a, b = 0, 1 print("Fibonacci Series:", end=" ") for _ in range(n): print(a, end=" ") a, b = b, a + b

Output

 
OUTPUT  :
Enter number of terms: 5
Fibonacci Series: 0 1 1 2 3 
 

Explanation:

  • Starts with 0, 1.
  • Each term = sum of previous two terms.
  • Complexity: O(n).

 

Example 2 : Advanced Program

def generate_fibonacci_series(n_terms): """ Generates the Fibonacci series up to n_terms. Args: n_terms (int): The number of terms to generate in the Fibonacci series. Returns: list: A list containing the Fibonacci series up to n_terms. """ if n_terms <= 0: return [] elif n_terms == 1: return [0] else: fib_series = [0, 1] while len(fib_series) < n_terms: next_term = fib_series[-1] + fib_series[-2] fib_series.append(next_term) return fib_series # Example usage: num_terms = 10 fibonacci_result = generate_fibonacci_series(num_terms) print(f"Fibonacci series up to {num_terms} terms:") print(fibonacci_result)

Output

 
OUTPUT  :
Fibonacci series up to 10 terms:
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
 

Explanation:

generate_fibonacci_series(n_terms) function:

  • This function takes an integer n_termsas input, representing the desired number of terms in the Fibonacci series.
  • Base Cases:
    • If n_termsis less than or equal to 0, an empty list is returned, as no terms can be generated.
    • If n_termsis 1, a list containing only 0 is returned, as it's the first term of the series.
  • Initialization:For n_terms greater than 1, a list fib_series is initialized with the first two terms: [0, 1].
  • Iteration:A while loop continues as long as the length of fib_series is less than n_terms.
    • Inside the loop, next_termis calculated by adding the last two elements of fib_series (fib_series[-1] and fib_series[-2]).
    • The next_termis then appended to the fib_series
  • Return Value:The function returns the fib_series list containing the generated Fibonacci numbers.