我正在用Python 2.7.6编写一个程序来计算斐波那契数列(1、2、3、5、8等)。这是代码(到目前为止):
x = int(input("Enter a number: "))
y = int(input("Enter the number that comes before it:"))
z = x + y
a = z + x
b = a + z
c = b + a
d = c + b
e = d + c
f = e + d
g = f + e
print x, z, a, b, c, d, e, f, g
有没有一种方法可以循环该过程,这样我就不必继续键入f = e + d和其他代码了?
当然,只需使用某种形式的loop即可。例如,如果要在以下位置列出前11个斐波纳契数x
:
fiblist = [x]
for _ in range(10):
z = x + y
fiblist.append(z)
x, y = z, x
print(fiblist)
(或使用循环而不是单个循环print
来改变输出的外观-与您的核心Q不相关)。
出于不同的目的(例如“列出序列中的所有数字,直到第一个数字大于100”),您可以轻松地调整循环(例如,代替for
使用while x <= 100:
)。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句