Python 程序:打印斐波那契序列
在此程序中,您将学习使用while循环打印斐波那契数列。
要理解此示例,您应该了解以下 [Python 编程]( "Python tutorial")主题:
斐波那契数列是 0、1、1、2、3、5、8 ...的整数序列。
前两项为 0 和 1。所有其他项均通过将前两项相加而获得。 这意味着第 n 个项是第(n-1)个和第(n-2)个项的总和。
源代码
# Program to display the Fibonacci sequence up to n-th term nterms = int(input("How many terms? ")) # first two terms n1, n2 = 0, 1 count = 0 # check if the number of terms is valid if 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 values n1 = n2 n2 = nth count += 1
输出:
How many terms? 7
Fibonacci sequence:
0
1
1
2
3
5
8
在这里,我们将术语数存储在nterms中。 我们将第一项初始化为 0,第二项初始化为 1。
如果项数大于 2,我们使用while循环通过将前两个项相加来查找序列中的下一个项。 然后,我们交换变量(对其进行更新)并继续进行该过程。
您也可以使用递归解决此问题: Python 程序:使用递归打印斐波那契序列。