斐波那契数列(Fibonacci sequence),又称黄金分割数列,指的是这样一个数列:1、1、2、3、5、8、13、21、34、……在数学上,斐波那契数列以如下被以递推的方法定义:F(1)=1,F(2)=1, F(n)=F(n-1)+F(n-2)(n>=3,n∈N*)
# 获取用户输入数据
num = int(input("你需要几项?"))
# 第一和第二项
n1 = 1
n2 = 1
count = 2
# 判断输入的值是否合法
if num <= 0:
print("请输入一个正整数。")
elif num == 1:
print("斐波那契数列:")
print(n1)
else:
print("斐波那契数列:")
print(n1, ",", n2, end=" , ")
while count < num:
nth = n1 + n2
print(nth, end=" , ")
# 更新值
n1 = n2
n2 = nth
count += 1
# def fib(number):
# n, a, b = 0, 1, 2
# while n < number:
# a, b = b, a + b
# n = n + 1
# print(len(str(b)))
#
# fib(20000)
# Python特有,组包拆包原理
def fib(number):
a = 1
b = 1
while a <= number: # 当斐波那契数小于等于number时结束循环
print(a, end=" ", flush=True)
a, b = b, a + b # python不借助变量交换两数的值
fib(1000) # 求n之内的斐波那契数列
def fib(x):
if x <= 2:
return 1
else:
return fib(x - 2) + fib(x - 1)
print(fib(10))
for i in range(1, 11):
print(fib(i), end=" , ")
输出30000以下的斐波那契数列,且每输出6个进行换行
a = [1, 1]
for i in range(2, 24):
num = (a[i - 1] + a[i - 2])
if num >= 30000:
break
else:
a.append(num)
# print(a[0:6])
# print(a[6:12])
# print(a[12:18])
# print(a[18:24])
for i in range(6):
print(a[i], end=" ")
print()
for i in range(6, 12):
print(a[i], end=" ")
print()
for i in range(12, 18):
print(a[i], end=" ")
print()
for i in range(18, 23):
print(a[i], end=" ")