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

What is wrong with my fibonacci sequence program that uses "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 中引用的语义错误是它 returns 值 None。 我刚刚开始学习 Python 并且我发现这个程序的问题已经有一段时间了。 我已经发现了如何使用 while 循环和递归编写斐波那契数列程序,但我只是很难使用这个过程。

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循环只运行一次。