【问题标题】:Python - Variable assignment & reassignment - what happened to X here?Python - 变量赋值和重新赋值 - 这里的 X 发生了什么?
【发布时间】: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


【解决方案1】:

您误解了您使用的运算符。在 Python 中,^ 运算符是按位异或。因此1 ^ 1 = 0。您对1 = 1 ^ 1 的假设是不正确的。如果您试图提升权力,请使用x**y

【讨论】:

  • 这正是我忽略的!非常感谢!
猜你喜欢
  • 2013-09-13
  • 1970-01-01
  • 2015-08-27
  • 2014-05-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-14
  • 2015-03-21
相关资源
最近更新 更多