Latest web development tutorials

Python recursive Fibonacci number

Document Object Reference Examples Python3

The following code uses a recursive way to generate Fibonacci columns:

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

def recur_fibo(n):
   """递归函数
   输出斐波那契数列"""
   if n <= 1:
       return n
   else:
       return(recur_fibo(n-1) + recur_fibo(n-2))


# 获取用户输入
nterms = int(input("您要输出几项? "))

# 检查输入的数字是否正确
if nterms <= 0:
   print("输入正数")
else:
   print("斐波那契数列:")
   for i in range(nterms):
       print(recur_fibo(i))

Execute the above code output results:

您要输出几项? 10
斐波那契数列:
0
1
1
2
3
5
8
13
21
34

Document Object Reference Examples Python3