Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python Print the Fibonacci Sequence Using Recursion

Python Print the Fibonacci Sequence Using Recursion

Document Object Reference Manual Python3 Examples

The Fibonacci sequence is a classic recursion problem in which each number is the sum of the two preceding numbers. The first two numbers 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

]

[

2

]

)

       

return

fib_sequence

Print the first 10 Fibonacci numbers

print

(

fibonacci

(

10

)

)

Code analysis:

  1. fibonacci The function takes an integer n as a parameter, indicating the length of the Fibonacci sequence to generate.
  2. If both the n is less than or equal to 0, return an empty list.
  3. If both the n equals 1, return a list containing only 0.
  4. If both the n equals 2, return a list containing 0 and 1.
  5. For n is greater than 2, recursively call fibonacci(n - 1) to generate the first n-1 Fibonacci numbers, then add the last two numbers together and append the result to the list.

Output result:

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

Document Object Reference Manual Python3 Examples