python的 a,b=b,a+b 和 a=b b=a+b 的区别

def fab(max):
    n, a, b = 0, 0, 1
    while n < max:
        print(b)
        a = b
        b = a + b
        n = n + 1
fab(10)

输出

1
1
2
4
8
16
32
64
128
256

def fab(max):
    n, a, b = 0, 0, 1
    while n < max:
        print(b)
        a, b = b, a + b
        n = n + 1
fab(10)

输出

1
1
2
3
5
8
13
21
34
55

我想这应该涉及到“=”赋值运算

a, b = b, a+b

先算“=”右边,b、a+b,然后赋值给a、b

应该分解为:

def fab(max):
    n, a, b = 0, 0, 1
    while n < max:
        print(b)
        c = b
        b = a + b
        a = c
        n = n + 1
fab(10)

输出:

1
1
2
3
5
8
13
21
34
55

 其他:

def fab(max):
    n, a, b = 0, 0, 1
    while n < max:
        yield b  
        c = b
        b = a + b
        a = c
        n = n + 1
for i in fab(10):
    print(i)

 

posted @ 2021-06-23 16:51  Gex  阅读(201)  评论(0编辑  收藏  举报