我正在进行的教程有以下程序
# This program calculates the Fibonacci sequence
a = 0
b = 1
count = 0
max_count = 20
while count < max_count:
count = count + 1
old_a = a # we need to keep track of a since we change it
print(old_a,end=" ") # Notice the magic end=" " in the print function arguments that
# keeps it from creating a new line
a = b
b = old_a + b
print() # gets a new (empty) line
代码很完美。但是,我无法弄清楚序列是如何计算的。 如何更改值以创建序列?
答案 0 :(得分:0)
如果删除所有无关的代码,那将更有意义:
while count < max_count:
old_a = a
a = b
b = old_a + b
old_a
可能让您感到困惑。这是写这篇文章的漫长道路:
a, b = b, a + b
将a
与b
和({同时),b
与a + b
进行互换。请注意, 与写入相同:
a = b
b = a + b
因为当您重新定义b
时,a
已经保留了新值,等于b
。
我也会通过在纸上书写来手动完成代码。
答案 1 :(得分:0)
此代码可以正常工作:
a, b = 0, 1
for _ in range(20):
print a
a, b = b, a+b