Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python Fibonacci Sequence

Python Fibonacci Sequence

Document Object Reference Manual Python3 Examples

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

:

print

(

"

Please enter a positive integer.

"

)

elif

nterms

==

1

:

print

(

"

Fibonacci sequence:

"

)

print

(

n1

)

else

:

print

(

"

Fibonacci sequence:

"

)

print

(

n1

,

"

,

"

,

n2

,

end

=

"

,

"

)

while

count

<

nterms

:

nth

=

n1

n2

print

(

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 ,

Document Object Reference Manual Python3 Examples