我的斐波那契python代码有什么问题?

时间:2019-10-19 19:47:23

标签: python fibonacci

请看一下我的代码。

numbers = [1,2]
times = int(input("How many numbersM (minimum is 2)"))
def fibonacci(numbers, times):
    for i in range(0, times):
        for j in numbers:
            numbers.append( numbers[j] + numbers[j+1])
        print(numbers[i])
fibonacci(numbers, times)

1 个答案:

答案 0 :(得分:1)

如果您这样运行代码,您将得到

IndexError: list index out of range

因为for j in numbers:numbers中值的循环,其中包含值1,这是您尝试访问numbers[j+1]时超出范围的索引,因为没有numbers[2]。为什么您仍然需要在那里的第二个for循环?您将使用numbers[i]numbers[i+1]访问倒数第二个值。无需遍历列表的其他值。

我已经删除了该循环,并且如果您这样运行代码,则:

numbers = [1,2]
times = int(input("How many numbersM (minimum is 2)"))
def fibonacci(numbers, times):
    for i in range(0, times):
        numbers.append( numbers[i] + numbers[i+1])
        print(numbers[i])
fibonacci(numbers, times)

例如,您会得到类似的东西

How many numbersM (minimum is 2)5
1
2
3
5
8