小白来提问!Python

写一个函数实现斐波那契数列(1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233,377…)。要求:接收一个参数,返回一个存着等量值的列表。如接收的参数值为5,则返回斐波那契数列前5个数的列表。

def fab(n):
    a, b = 1, 1
    for i in range(n):
        yield b
        a, b = b, a+b

 

# -*- coding: UTF-8 -*-

# 获取用户输入数据
nterms = int(input("你需要几项?"))

# 第一和第二项
n1 = 0
n2 = 1
count = 2
#列表
list1=[];
# 判断输入的值是否合法
if nterms <= 0:
    print("请输入一个正整数。")
elif nterms == 1:
    list1.append(n1)
elif nterms == 2:
    list1.append(n2)
else:
    while count < nterms+2:
        nth = n1 + n2
        list1.append(nth)
        # 更新值
        n1 = n2
        n2 = nth
        count += 1
print(list1)