Python Fibonacci: Generate First n Terms

You can use the following code to output the first n terms of the Fibonacci sequence:

def fibonacci(n):
    fib_list = [0, 1]
    for i in range(2, n):
        fib_list.append(fib_list[i-1] + fib_list[i-2])
    return fib_list

n = int(input("请输入要输出的斐波那契数列的项数:"))
print(fibonacci(n))

In this code snippet, we have defined a function called “fibonacci” that takes a parameter n and returns the first n terms of the Fibonacci sequence. We then prompt the user for the number of terms they want to see in the Fibonacci sequence and call the fibonacci function to output the result.

bannerAds