Python Print Fibonacci Sequence

Document 对象参考手册Python3 Examples

The Fibonacci sequence is a classic mathematical problem where each number is the sum of the two preceding numbers. The first two numbers in the sequence are usually defined as 0 and 1. We can write a simple Python program to print the first n terms of the Fibonacci sequence.

Example

def fibonacci(n):
    fib_sequence = []
    a, b = 0, 1
    for _ in range(n):
        fib_sequence.append(a)
        a, b = b, a + b
    return fib_sequence

n = 10  # Print the first 10 terms
print(fibonacci(n))

Code explanation:

  1. def fibonacci(n):Defines a function namedfibonaccithat takes one parametern, representing the number of terms of the Fibonacci sequence to print.
  2. fib_sequence = []Initializes an empty listfib_sequenceto store the Fibonacci sequence.
  3. a, b = 0, 1Initializes two variablesaandbrepresenting the first two numbers of the Fibonacci sequence.
  4. for _ in range(n):Uses a loop to generate the firstnterms of the Fibonacci sequence.
  5. fib_sequence.append(a)Adds the currentavalue to thefib_sequencelist.
  6. a, b = b, a + bUpdatesaandbso thatabecomesb,bbecomesa + b, i.e., the next Fibonacci number.
  7. return fib_sequenceReturns the generated Fibonacci sequence.
  8. n = 10Sets the number of terms of the Fibonacci sequence to print to 10.
  9. print(fibonacci(n))Calls thefibonaccifunction and prints the result.

Output:

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

Document 对象参考手册Python3 Examples

Other extensions