请看一下我的代码。
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)
答案 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