用Python实现斐波那契数列,费波那契数列由0和1开始,之后的费波那契系数就是由之前的两数相加而得出,例如前 斐波那契数列 0, 1, 1, 2, 3, 5, 8, 13, 21, 34。用数学方法可定义为如图所示:
# -*- coding : UTF-8 -*-
nums = int(input("你需要几项(1~50)?"))
# 第一和第二项
Fibo_1 = 0
Fibo_2 = 1
count = 2
# 判断输入的值是否合法
if nums <= 0 or nums >= 51 :
print("请输入一个不大于50的正整数。")
elif nums == 1:
print("斐波那契数列:")
print(Fibo_1)
else:
print("斐波那契数列:")
print(Fibo_1,",",Fibo_2,end=" , ")
while count < nums:
Fibo = Fibo_1 + Fibo_2
print(Fibo,end=" , ")
# 更新值
Fibo_1 = Fibo_2
Fibo_2 = Fibo
count += 1