代码使用递归的方式来生成斐波那契数列:
# 利用递归函数来生成斐波那契数列
# 定义递归函数
def recur_fibo( n ):
if n <= 1:
return n
else:
return (recur_fibo(n-1)+ recur_fibo(n-2))
# 用户输入数据
user_num = int(input("你想得到的项数:"))
if user_num < 0:
print("请输入正数!")
else:
print("斐波那契数列:")
for i in range(0, user_num):
print(recur_fibo(i), end=",")
结果:
你想得到的项数:8
斐波那契数列:
0,1,1,2,3,5,8,13,
Process finished with exit code 0