Python Print Fibonacci Sequence
The Fibonacci sequence is a classic mathematical problem where each number is the sum of the two preceding numbers. The first two numbers in the sequence are usually defined as 0 and 1. We can write a simple Python program to print the first n terms of the Fibonacci sequence.
Example
def fibonacci(n):
fib_sequence = []
a, b = 0, 1
for _ in range(n):
fib_sequence.append(a)
a, b = b, a + b
return fib_sequence
n = 10 # Print the first 10 terms
print(fibonacci(n))
fib_sequence = []
a, b = 0, 1
for _ in range(n):
fib_sequence.append(a)
a, b = b, a + b
return fib_sequence
n = 10 # Print the first 10 terms
print(fibonacci(n))
Code explanation:
def fibonacci(n):Defines a function namedfibonaccithat takes one parametern, representing the number of terms of the Fibonacci sequence to print.fib_sequence = []Initializes an empty listfib_sequenceto store the Fibonacci sequence.a, b = 0, 1Initializes two variablesaandbrepresenting the first two numbers of the Fibonacci sequence.for _ in range(n):Uses a loop to generate the firstnterms of the Fibonacci sequence.fib_sequence.append(a)Adds the currentavalue to thefib_sequencelist.a, b = b, a + bUpdatesaandbso thatabecomesb,bbecomesa + b, i.e., the next Fibonacci number.return fib_sequenceReturns the generated Fibonacci sequence.n = 10Sets the number of terms of the Fibonacci sequence to print to 10.print(fibonacci(n))Calls thefibonaccifunction and prints the result.
Output:
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]Other extensions
Python3 Examples