我的斐波那契数列程序使用"for loop"有什么问题


def fibonacci(n):
    terms = [0,1]
    i = 2
    for i in terms[2:n+1]:
        terms.append(terms[i-1] + terms[i-2])
        return terms[n]
user_input= input ('Write the number order by which you want to know its corresponding value in the fibonacci sequence')
fibonacci_user_input = fibonacci(user_input)
print fibonacci_user_input

我在pyscripter Python 2.7.9中引用的语义错误是我在此程序中使用的是它返回值None。我刚刚开始学习Python,现在已经有一段时间了,我一直在发现这个程序出了问题。我已经发现了如何使用循环和递归编写fibonacci序列程序,而我只是很难使用此过程。

for i in terms[2:n+1]:

应该是:

for i in range(2, n+1):

您正在添加到terms,您不想在其当前内容上迭代。

此行

        terms.append(terms[i-1] + terms[i-2])

无论n的值多大,for循环中仅运行一次。

最新更新