Python 使用遞歸斐波那契數(shù)列

Document 對(duì)象參考手冊(cè) Python3 實(shí)例

以下代碼使用遞歸的方式來(lái)生成斐波那契數(shù)列:

# Filename : test.py
# author by : www.o2fo.com

def recur_fibo(n):
   """遞歸函數(shù)
   輸出斐波那契數(shù)列"""
   if n <= 1:
       return n
   else:
       return(recur_fibo(n-1) + recur_fibo(n-2))


# 獲取用戶輸入
nterms = int(input("您要輸出幾項(xiàng)? "))

# 檢查輸入的數(shù)字是否正確
if nterms <= 0:
   print("輸入正數(shù)")
else:
   print("斐波那契數(shù)列:")
   for i in range(nterms):
       print(recur_fibo(i))

執(zhí)行以上代碼輸出結(jié)果為:

您要輸出幾項(xiàng)? 10
斐波那契數(shù)列:
0
1
1
2
3
5
8
13
21
34

Document 對(duì)象參考手冊(cè) Python3 實(shí)例