Python Using Recursion to Print the Fibonacci Sequence

Document 对象参考手册Python3 Examples

The Fibonacci sequence is a classic recursion problem, where each number is the sum of the previous two numbers. The first two numbers of the sequence are usually 0 and 1. We can use a recursive function to generate the Fibonacci sequence.

Example

def fibonacci(n):
    if n <= 0:
        return []
    elif n == 1:
        return [0]
    elif n == 2:
        return [0, 1]
    else:
        fib_sequence = fibonacci(n - 1)
        fib_sequence.append(fib_sequence[-1] + fib_sequence[-2])
        return fib_sequence

# Print the first 10 Fibonacci numbers
print(fibonacci(10))

Code analysis:

  1. fibonacciThe function accepts an integernas a parameter, indicating the length of the Fibonacci sequence to be generated.
  2. Ifnis less than or equal to 0, return an empty list.
  3. Ifnequals 1, return a list containing only 0.
  4. Ifnequals 2, return a list containing 0 and 1.
  5. Forngreater than 2, recursively callfibonacci(n - 1)to generate the firstn-1Fibonacci numbers, then add the last two numbers together and append them to the list.

Output result:

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

Document 对象参考手册Python3 Examples

Other Extensions