我写了一个简单的程序来自动化斐波那契数列,但它不工作,我不明白为什么
I've written a simple program to automate the Fibonacci sequence and it's not working and I can't figure out why
我试图更好地理解 python 中的函数,并决定尝试自动化斐波那契数列。到目前为止,这是我的代码,它没有做它应该做的事情。我不知道为什么它不起作用。有人可以指出我的错误吗?
我使用 stop 变量作为明确的停止,而 length 变量告诉程序我希望它执行代码多远。下面是我的代码:
length = 6
stop = 10
def append_sum(lst):
while length <= stop:
return lst.append(lst[-1] + lst[-2])
print(append_sum([1, 1, 2]))
对于这样的事情,我会 Google 它。
a = int(input('Give amount: '))
def fib(n):
a, b = 0, 1
for _ in range(n):
yield a
a, b = b, a + b
print(list(fib(a)))
结果:
Give amount: 10
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
您代码中的长度变量没有改变,因此停靠点不起作用。同样即使它这样做了,你 return 列表在它进入 while 函数之后,所以最多它会做一次迭代。
lst.append() 会改变列表,但不会 return 它的副本,所以你不能 return lst.append()
我试图更好地理解 python 中的函数,并决定尝试自动化斐波那契数列。到目前为止,这是我的代码,它没有做它应该做的事情。我不知道为什么它不起作用。有人可以指出我的错误吗?
我使用 stop 变量作为明确的停止,而 length 变量告诉程序我希望它执行代码多远。下面是我的代码:
length = 6
stop = 10
def append_sum(lst):
while length <= stop:
return lst.append(lst[-1] + lst[-2])
print(append_sum([1, 1, 2]))
对于这样的事情,我会 Google 它。
a = int(input('Give amount: '))
def fib(n):
a, b = 0, 1
for _ in range(n):
yield a
a, b = b, a + b
print(list(fib(a)))
结果:
Give amount: 10
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
您代码中的长度变量没有改变,因此停靠点不起作用。同样即使它这样做了,你 return 列表在它进入 while 函数之后,所以最多它会做一次迭代。 lst.append() 会改变列表,但不会 return 它的副本,所以你不能 return lst.append()