其第一、第二项分别为1、1,其后每一项都是前两项之和,求该数列的前20项。

 

nterms = int(input("请输入n的值(n>2):"))
 
# 第一和第二项
n1 = 1
n2 = 1
count = 2
 
# 判断输入的值是否合法
n = []
if nterms <= 0:
    print("请输入一个正整数。")
elif nterms == 1:

    print("前{}项斐波那契数列的值为:".format(nterms))
    n.append(n1)
else:
    print("前{}项斐波那契数列的值为:".format(nterms))
    n.append(n1)
    n.append(n2)
    while count < nterms:
        nth = n1 + n2
        n.append(nth)
        # 更新值
        n1 = n2
        n2 = nth
        count += 1
print(n)