原文: https://www.programiz.com/python-programming/examples/fibonacci-sequence
在此程序中,您将学习使用while循环打印斐波那契数列。
要理解此示例,您应该了解以下 Python 编程主题:
斐波那契数列是 0、1、1、2、3、5、8 …的整数序列。
前两项为 0 和 1。所有其他项均通过将前两项相加而获得。 这意味着第 n 个项是第(n-1)个和第(n-2)个项的总和。
源代码
# Program to display the Fibonacci sequence up to n-th termnterms = int(input("How many terms? "))# first two termsn1, n2 = 0, 1count = 0# check if the number of terms is validif nterms <= 0:print("Please enter a positive integer")elif nterms == 1:print("Fibonacci sequence upto",nterms,":")print(n1)else:print("Fibonacci sequence:")while count < nterms:print(n1)nth = n1 + n2# update valuesn1 = n2n2 = nthcount += 1
输出
How many terms? 7Fibonacci sequence:0112358
在这里,我们将术语数存储在nterms中。 我们将第一项初始化为 0,第二项初始化为 1。
如果项数大于 2,我们使用while循环通过将前两个项相加来查找序列中的下一个项。 然后,我们交换变量(对其进行更新)并继续进行该过程。
您也可以使用递归解决此问题: Python 程序:使用递归打印斐波那契序列。
