Python Fibonacci Sequence
The Fibonacci sequence is 0, 1, 1, 2, 3, 5, 8, 13; specifically, term 0 is 0 and term 1 is the first 1. From the third term on, each term equals the sum of the previous two.
The Python code to implement the Fibonacci sequence is as follows:
Example (Python 3.0+)
-- coding: UTF-8 --
Filename : test.py
author by : www.runoob.com
Python Fibonacci Sequence Implementation
Get user input
nterms
=
int
(
input
(
"
How many terms do you need?
"
)
)
The first and second terms
n1
=
0
n2
=
1
count
=
2
Check whether the input value is valid
if
nterms
<=
0
:
(
"
Please enter a positive integer.
"
)
elif
nterms
==
1
:
(
"
Fibonacci sequence:
"
)
(
n1
)
else
:
(
"
Fibonacci sequence:
"
)
(
n1
,
"
,
"
,
n2
,
end
=
"
,
"
)
while
count
<
nterms
:
nth
=
n1
n2
(
nth
,
end
=
"
,
"
)
Update the values
n1
=
n2
n2
=
nth
count
+=
1
The output of the code above is:
你需要几项? 10
Fibonacci sequence:
0 , 1 , 1 , 2 , 3 , 5 , 8 , 13 , 21 , 34 ,
Python3 Examples