📅  最后修改于: 2023-12-03 14:47:24.580000             🧑  作者: Mango
The Fibonacci sequence is a mathematical series of numbers where each number is the sum of the two preceding ones, usually starting with 0 and 1.
In Python, there are multiple ways to implement the Fibonacci sequence, but one of the most commonly used methods is using loops. Let's explore this implementation and understand how it works.
def fibonacci(n):
"""
Calculate the Fibonacci sequence up to the nth term.
Arguments:
n -- an integer representing the term up to which the sequence should be calculated
Returns:
A list containing the Fibonacci sequence up to the nth term.
"""
sequence = [0, 1] # Initialize the sequence with the first two terms
if n <= 2:
return sequence[:n] # Return the initial part of the sequence if n is 0, 1, or 2
while len(sequence) < n:
new_number = sequence[-1] + sequence[-2] # Calculate the next number in the sequence
sequence.append(new_number) # Add the new number to the sequence
return sequence
To use the above implementation and calculate the Fibonacci sequence, you can simply call the fibonacci
function and provide the desired term.
>>> fibonacci(10)
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
The above example calculates the Fibonacci sequence up to the 10th term and returns the result as a list.
The Fibonacci sequence is a fascinating series of numbers that has applications in various mathematical and computational problems. By using Python, you can easily calculate this sequence using a simple loop implementation.
Markdown