Skip to main content
 首页 » 编程设计

python之斐波那契与 Python : IndexError: list index out of range

2025年05月04日15qlqwjy

我试图编写一个程序来使用 Python 计算斐波那契数:

n = int(input()) 
 
def fib(n): 
    a = [] 
    if (n <=1): 
        return n 
    else: 
        for i in range(2, n): 
            a.append(a[-1] + a[-2]) 
        return a[i] 
print (fib(n)) 

但是,我无法打印出预期的结果。例如,我输入数字 8 后,弹出以下消息:

Traceback (most recent call last): 
  File "fibonacci.py", line 11, in <module> 
    print (fib(n)) 
  File "fibonacci.py", line 9, in fib 
    a.append(a[-1] + a[-2]) 
IndexError: list index out of range 

过程中出了什么问题?提前致谢。

请您参考如下方法:

您需要用斐波那契数列的前 2 个数字填充您的列表:

a = [0, 1]