Skip to content

fibonacci python

Certainly! You can create a Python program to generate Fibonacci numbers using various methods. Here’s a simple example using a loop:

def fibonacci(n):
    fib_sequence = [0, 1]

    while len(fib_sequence) < n:
        next_number = fib_sequence[-1] + fib_sequence[-2]
        fib_sequence.append(next_number)

    return fib_sequence

# Change the value of 'n' to generate a different number of Fibonacci numbers
n = 10
result = fibonacci(n)
print(result)

In this code:

  1. We define a function fibonacci(n) that takes an integer n as an input and generates the first n Fibonacci numbers.
  2. We initialize a list fib_sequence with the first two Fibonacci numbers, 0 and 1.
  3. We use a while loop to calculate the next Fibonacci numbers until the length of fib_sequence reaches n.
  4. The next Fibonacci number is calculated by adding the last two numbers in fib_sequence.
  5. The generated Fibonacci numbers are stored in the list fib_sequence, and the list is returned as the result.
  6. You can change the value of n to generate a different number of Fibonacci numbers.

When you run this code with n = 10, it will print the first 10 Fibonacci numbers:

[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

You can adjust the value of n as needed to generate more or fewer Fibonacci numbers.

Leave a Reply

Your email address will not be published. Required fields are marked *

error

Enjoy this blog? Please spread the word :)