蟒蛇 a, b = b, a +b [英] Python a, b = b, a +b
本文介绍了蟒蛇 a, b = b, a +b的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我的第一个问题,我开始学习 Python.是否有区别:
This is my first question and I started to learn Python. Is there a difference between:
a, b = b, a + b
和
a = b
b = a + b
当你在下面的例子中写它时,它显示了不同的结果.
When you write it in below example it shows different results.
def fib(n):
a, b = 0, 1
while a < n:
print(a, end=' ')
a, b = b, a + b
print()
fib(1000)
和
def fib(n):
a, b = 0, 1
while a < n:
print(a, end=' ')
a = b
b = a + b
print()
fib(1000)
推荐答案
在 a, b = b, a + b
中,右边的表达式在赋值给左边之前先求值手边.所以等价于:
In a, b = b, a + b
, the expressions on the right hand side are evaluated before being assigned to the left hand side. So it is equivalent to:
c = a + b
a = b
b = c
在第二个例子中,a
的值在 b = a + b
运行时已经改变了.因此,结果是不同的.
In the second example, the value of a
has already been changed by the time b = a + b
is run. Hence, the result is different.
这篇关于蟒蛇 a, b = b, a +b的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文