In this tutorial, we will learn how to print the Fibonacci sequence using recursion in Python. We will cover the basic concept of recursion and implement a recursive function to generate the Fibonacci sequence.
The Fibonacci sequence is a series of numbers where each number is the sum of the two preceding ones, usually starting with 0 and 1. The sequence starts as 0, 1, 1, 2, 3, 5, 8, and so on.
The syntax to print the Fibonacci sequence using recursion in Python is:
def fibonacci_recursive(n):
if n <= 0:
return []
elif n == 1:
return [0]
elif n == 2:
return [0, 1]
else:
seq = fibonacci_recursive(n - 1)
seq.append(seq[-1] + seq[-2])
return seq
We can use a recursive method to generate and print the Fibonacci sequence up to the n-th term.
For example,
fibonacci_recursive
that takes one parameter n
.n
is less than or equal to 0, return an empty list; if n
is 1, return a list with [0]; if n
is 2, return a list with [0, 1].n
, call the function recursively with n - 1
.def fibonacci_recursive(n):
if n <= 0:
return []
elif n == 1:
return [0]
elif n == 2:
return [0, 1]
else:
seq = fibonacci_recursive(n - 1)
seq.append(seq[-1] + seq[-2])
return seq
# Print the first 10 terms of the Fibonacci sequence
fib_sequence = fibonacci_recursive(10)
print(' '.join(map(str, fib_sequence)))
0 1 1 2 3 5 8 13 21 34