输入:
x, y = 20, 60
y, x, y = x, y-10, x+10
print(x, y)
输出:
50 30
我期望的是?
x = 20
y = 60
y = x = 20
x = y-10 = 20-10 = 10
y = x + 10 = 20
预期输出:
10 20
为什么不是这种情况?是因为首先对表达式求值,然后才给变量赋值?
答案 0 :(得分:7)
右侧完全排在左侧之前。然后从左到右评估左侧。
x, y = 20, 60
# x = 20, y = 60
# ----------------------
y, x, y = x, y-10, x+10
# Evaulate the right first:
# x, y-10, x+10 = 20, 50, 30
# So now we have
# y, x, y = 20, 50, 30
# Now it goes left to right so:
# y = 20
# x = 50
# y = 30 --> note this overwrote the first y assignment
print(x, y)
因此
50 30