交换发生了吗?

Did the swap happened?

我在 CodeChef 推特 https://twitter.com/codechef/status/941329495046459395 中找到了这段代码。它是用 C 语言编写的。我是在 Python3 中完成的。这是我的代码:

def vegas(a,b):
    temp = a
    a = b
    b = temp
a = 6
b = 9
print(a,b)
vegas(a,b)
print(a,b)

这就是答案:

6 9
6 9

我的问题是,为什么我的 'vegas' 函数没有交换变量 'a' 和 'b'

的值

它不会按照您预期的方式工作。 This question 正在完整回答这个问题。简而言之:Python 将参数 ab 变成两个仅在 vegas 中可见的变量。它们以 ab 的值启动,但与外部 ab 变量无关。

要使您的代码正常工作,请执行以下操作:

def vegas(a,b):
    temp = a
    a = b
    b = temp
    return a,b
a = 6
b = 9
print(a,b)
a,b = vegas(a,b)
print(a,b)

此外,您可能有兴趣知道可以使用 a,b = b,a

交换两个值

是也不是... 函数 vegas 完成工作但从不 returns a 和 b 所以 a 和 b 仍然是 6 和 9 在外面。 Arguments are passed by assignment in Python.

可以看到more here

此代码片段是一个笑话 "what happens in vegas stays in vegas" 因为该函数不会影响变量的值。为了影响值,函数需要 return 交换的结果。如果没有 return 语句,函数将不会影响变量,因为函数会创建自己的临时变量以在函数内使用。