python--斐波那契(100以内)for和while两种

num = [0, 1]
def fbnq(num):
    for i in range(100):
        sub = (num[-1] + num[-2])

        print(sub)
        if sub >= 100:
            break
        num.append(sub)
fbnq(num)
print(num)

上述是for循环

小面是while

nterms = int(input("你需要几项?"))
n1 = 0
n2 = 1
count = 2
if nterms <= 0:
    print("请输入一个整数")
elif nterms == 1:
    print("斐波那契数列:")
    print(n1)
else:
    print("斐波那契数列:")
    print(n1, ",", n2, end=",")
    while count < nterms:
        nth = n1 + n2
        print(nth, end=",")
        n1 = n2
        n2 = nth
        count += 1

猜你喜欢

转载自blog.csdn.net/weixin_55821558/article/details/124458362