Skip to main content
 首页 » 编程设计

python之斐波那契的 `a, b = b, a+b` 和 `a = b; b = a+b` 有什么区别

2025年05月04日2398°冷暖

<分区>

我刚接触python所以想问你一个问题..

之前我在写斐波那契函数时尝试替换

a, b = b, a+b 

与

a = b 
b = a + b 

相信这是同一件事,但我注意到输出不同(而且是错误的) 这两个代码不应该做同样的事情吗? 这是完整的代码:

#!/usr/bin/env python 
# -*- coding: utf-8 -*- 
 
def main(args): 
    fibonacci(1000) 
    return 0 
 
def fibonacci(n): 
    a, b = 0, 1 
    while b < n: 
         print b, 
         a, b = b, a+b # if I comment this and decomment the two line below it shows me a different output  
        # a = b 
        # b = a + b 
 
if __name__ == '__main__': 
    import sys 
    sys.exit(main(sys.argv))