Python Code for Fibonacci Series

PHOTO EMBED

Sat May 31 2025 05:10:23 GMT+0000 (Coordinated Universal Time)

Saved by @FreeYt #python

def fibonacci_series(n):
    fib_sequence = [0, 1]  # Starting values for Fibonacci series

    while len(fib_sequence) < n:
        # Add the last two numbers to get the next one
        next_number = fib_sequence[-1] + fib_sequence[-2]
        fib_sequence.append(next_number)

    return fib_sequence[:n]  # Return only first 'n' elements

# Example usage
num_terms = int(input("Enter the number of terms: "))
print("Fibonacci Series:")
print(fibonacci_series(num_terms))
content_copyCOPY

Function Definition: def fibonacci_series(n): defines a function that returns the first n numbers of the Fibonacci series. Initial Values: fib_sequence = [0, 1] starts the series with 0 and 1. Loop to Generate the Series: The while loop runs until the list has n elements. It calculates the next number by summing the last two: next_number = fib_sequence[-1] + fib_sequence[-2] Appending to the Sequence: fib_sequence.append(next_number) adds the new number to the list. Return Result: After the loop, it returns the list with the first n Fibonacci numbers. User Input & Output: The program asks the user how many terms they want and prints the result.

https://freeytthumbnail.com/