Introduction
The Fibonacci sequence is a series of numbers in which each number is the sum of the two preceding ones. It starts with 0 and 1, and the next number is the sum of the previous two numbers. In this challenge, you will write a function that generates a list containing the Fibonacci sequence up until the nth term.
Fibonacci
Write a function called fibonacci(n) that takes an integer n as its parameter and returns a list containing the Fibonacci sequence up until the nth term.
To solve this problem, you can follow these steps:
- Create an empty list called
sequence. - If
nis less than or equal to 0, append 0 to thesequencelist and return the list. - Append 0 and 1 to the
sequencelist. - Use a while loop to add the sum of the last two numbers of the
sequencelist to the end of the list, until the length of the list reachesn. - Return the
sequencelist.
def fibonacci(n):
if n <= 0:
return [0]
sequence = [0, 1]
while len(sequence) <= n:
next_value = sequence[len(sequence) - 1] + sequence[len(sequence) - 2]
sequence.append(next_value)
return sequence
fibonacci(7) ## [0, 1, 1, 2, 3, 5, 8, 13]
Summary
In this challenge, you have learned how to generate a list containing the Fibonacci sequence up until the nth term. You have also learned how to use a while loop to add the sum of the last two numbers of a list to the end of the list.