【发布时间】:2018-12-11 17:53:25
【问题描述】:
我正在研究一个关于变量的谜题,但无法弄清楚我的变量如何在以下过程中从 1 变为 0:
x = 1
y = 0
# first assignment
x = x^y
print(f'x value is {x} after reassignment')
# x value is 1 after reassignment
# second assignment
y = y^x
print(f'y value is {y} after reassignment')
# y value is 1 after reassignment
print(f'{y} = {y} ^ {x}')
# returns 1 = 1 ^ 1
# x value is now 1 but somehow ZERO after the assignment below
x = x^y
print(f'{x} = {y} ^ {x} how did x become zero from this assignment?')
# returns 0 = 1 ^ 0
我想了解 x 是如何变为零的。谢谢!
【问题讨论】:
-
这很简单:
1 ^ 1 == 0。更大的图景是,这种类型的重复赋值是在没有临时变量的情况下交换两个整数值的老技巧。 -
1 ^ 1不是1- 您在f'{y} = {y} ^ {x}'中混淆了y的分配前和分配后值。
标签: python variables global-variables variable-assignment