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

Python Recursive Fibonacci Sequence

Python Recursive Fibonacci Sequence

Document Object Reference Manual Python3 Examples

The following code uses recursion to generate the Fibonacci sequence:

Example (Python 3.0+)

Filename : test.py

author by : www.runoob.com

def

recur_fibo

(

n

)

:

"""

Recursive function to output the Fibonacci sequence

"""

if

n

<=

1

:

return

n

else

:

return

(

recur_fibo

(

n

1

)

recur_fibo

(

n

2

)

)

Get user input

nterms

=

int

(

input

(

"

How many terms would you like?

"

)

)

Check whether the input number is valid

if

nterms

<=

0

:

print

(

"

Enter a positive number

"

)

else

:

print

(

"

Fibonacci sequence:

"

)

for

i

in

range

(

nterms

)

:

print

(

recur_fibo

(

i

)

)

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