Python printing the Fibonacci sequence
The Fibonacci sequence is a classic mathematical problem where each number is the sum of the previous two. The first two numbers of the sequence are usually defined as 0 and 1. We can use Python to write a simple 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
(
fibonacci
(
n
)
)
Code analysis:
def fibonacci(n):defines a class namedfibonaccifunction, which takes a parametern, representing the number of Fibonacci terms to print.fib_sequence = []Initialize an empty listfib_sequence, used to store the Fibonacci sequence.a, b = 0, 1Initialize two variablesaandb, representing the first two numbers of the Fibonacci sequence.for _ in range(n):Use a loop to generate the firstnterms of the Fibonacci sequence.fib_sequence.append(a)Add the currentavalue tofib_sequencelist.a, b = b, a + bupdateaandbvalue, so thatabecomesb,bbecomesa + b, which is the next Fibonacci number.return fib_sequenceReturn the generated Fibonacci sequence.n = 10Set the number of Fibonacci terms to print to 10.print(fibonacci(n))calledfibonaccifunction and print the result.
Output result:
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
Python3 Examples