Python:fib函数中的for循环不';我不明白

Python:fib函数中的for循环不';我不明白,python,function,loops,Python,Function,Loops,在Python课程中,我有一个关于斐波那契数的练习。 下面是第4.1.5.7章的完整内容 我的问题是关于函数本身。特别是我对环路内部发生的事情感到困惑: for i in range(3, n + 1): sum = elem1 + elem2 elem1, elem2 = elem2, sum return sum 在第三行中,您可以看到elem1逗号elem2等于elem2逗号和。这是什么意思 有人能一步一步地解释我如何解释这个循环的内容吗 第4.1.5.7章的完整文本

在Python课程中,我有一个关于斐波那契数的练习。 下面是第4.1.5.7章的完整内容

我的问题是关于函数本身。特别是我对环路内部发生的事情感到困惑:

for i in range(3, n + 1):
    sum = elem1 + elem2
    elem1, elem2 = elem2, sum
return sum

在第三行中,您可以看到elem1逗号elem2等于elem2逗号和。这是什么意思

有人能一步一步地解释我如何解释这个循环的内容吗


  • 第4.1.5.7章的完整文本:
一些简单函数:斐波那契数 你熟悉斐波那契数吗

它们是使用非常简单的规则构建的整数序列:

序列的第一个元素等于一(Fib1=1) 第二个也等于一(Fib2=1) 后面的每个数都是前面两个数的和(Fibi=Fibi-1+Fibi-2) 以下是一些Fibonacci数:

fib1 = 1
fib2 = 1
fib3 = 1 + 1 = 2
fib4 = 1 + 2 = 3
fib5 = 2 + 3 = 5
fib6 = 3 + 5 = 8
fib7 = 5 + 8 = 13
您认为如何将其作为一个函数来实现

让我们创建fib函数并测试它。这是:

def fib(n):
    if n < 1:
         return None
    if n < 3:
        return 1

    elem1 = elem2 = 1
    sum = 0
    for i in range(3, n + 1):
        sum = elem1 + elem2
        elem1, elem2 = elem2, sum
    return sum

for n in range(1, 10): # testing
    print(n, "->", fib(n))


来源于思科网络学院-课程名称:PCAP-Python编程要点-模块4,第4.1.5.7章,题为“创建函数|斐波那契数”。

在Python中,
a,b=c,d
表示“设置
a=c
b=d

这句话几乎和说的一样

elem1 = elem2
elem2 =  sum
唯一的区别是它们“同时”发生。这可能很重要。例如,如果我写:

x, y = y, x
它交换元素,而

x = y
y = x 

没有。

对于代码elem1,elem2=elem2,sum的意思是:elem1=elem2,elem2=sum,或者您可以将其解释为i,j=1,10,其中i=1和j=10

elem1 = elem2 = 1 # Set the first two numbers of the fib sequence to 1
sum = 0
for i in range(3, n + 1): # if n is 3, we get -- for i in range(3,4), where i will only be 3 -- if n is 4, i will be 3, then 4 etc. 
    sum = elem1 + elem2 # First find the third number of the sequence, and during other iteration, the third will be shifted to the fourth, fifth, etc.
    elem1, elem2 = elem2, sum # Now shift the variables so the first number is the second, and the second is the sum(third) During each loop, we shift them again
return sum

您应该阅读有关python解包的内容。“elem1逗号elem2等于elem2逗号和”更准确地说,
=
应该表示为“已分配”。这将帮助您避免在编程中混淆
=
=
x = y
y = x 
elem1 = elem2 = 1 # Set the first two numbers of the fib sequence to 1
sum = 0
for i in range(3, n + 1): # if n is 3, we get -- for i in range(3,4), where i will only be 3 -- if n is 4, i will be 3, then 4 etc. 
    sum = elem1 + elem2 # First find the third number of the sequence, and during other iteration, the third will be shifted to the fourth, fifth, etc.
    elem1, elem2 = elem2, sum # Now shift the variables so the first number is the second, and the second is the sum(third) During each loop, we shift them again
return sum