Python Print the Fibonacci Sequence Using Recursion
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
]
- fib_sequence
[
2
]
)
return
fib_sequence
Print the first 10 Fibonacci numbers
(
fibonacci
(
10
)
)
Code analysis:
fibonacciThe function takes an integernas a parameter, indicating the length of the Fibonacci sequence to generate.- If both the
nis less than or equal to 0, return an empty list. - If both the
nequals 1, return a list containing only 0. - If both the
nequals 2, return a list containing 0 and 1. - For
nis greater than 2, recursively callfibonacci(n - 1)to generate the firstn-1Fibonacci 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]
Python3 Examples