Python Using Recursion to Print the Fibonacci Sequence
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))
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:
fibonacciThe function accepts an integernas a parameter, indicating the length of the Fibonacci sequence to be generated.- If
nis less than or equal to 0, return an empty list. - If
nequals 1, return a list containing only 0. - If
nequals 2, return a list containing 0 and 1. - For
ngreater 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]Other Extensions
Python3 Examples