Python为什么不';t变量在函数之后发生变化?

Python为什么不';t变量在函数之后发生变化?,python,Python,我正在为我的CompSci课程做一个家庭作业,出现了这个问题: x = 6 def fun(x): y = x**2 x = y return(x) fun(x) 运行此操作时,打印出来的值为36,但当运行打印(x)时,x仍然是6 我想知道为什么会这样;为什么x不变 谢谢 x = 6 def fun(x): y = x**2 x = y return(x) # Reassign the returned value since the scope

我正在为我的CompSci课程做一个家庭作业,出现了这个问题:

x = 6
def fun(x):
    y = x**2
    x = y
    return(x)
fun(x)
运行此操作时,打印出来的值为36,但当运行打印(x)时,x仍然是6

我想知道为什么会这样;为什么x不变

谢谢

x = 6
def fun(x):
    y = x**2
    x = y
    return(x)
# Reassign the returned value since the scope changed.
x = fun(x)


如果要修改函数中的全局变量,请使用全局关键字:

global x

否则,将在赋值过程中创建局部变量。

这是因为“全局x”不同于“fun x”,“fun x”重叠/屏蔽了“全局x”,您可以对其执行任何操作,然后它就不存在了。掩码不在那里,所以以前的“全局x”再次是当前的“x”

如上所述,您可以通过在函数中使用“global x”来克服这一问题,请注意fun1和fun2之间的区别

x = 10
print "'x' is ", x
def fun1(x):
    print "'x' is local to fun1 and is", x
    x = x**2
    print "'x' is local to fun1 and is now", x

def fun2():
    global x
    print "'x' is global and is", x
    x = x ** 2
    print "'x' is global and is now", x
print "'x' is still", x
fun1(x)
print "'x' is not local to fun anymore and returns to it's original value: ", x
fun2()
print "'x' is not local to fun2 but since fun2 uses global 'x' value is now:", x
输出:

'x' is  10
'x' is still 10
'x' is local to fun1 and is 10
'x' is local to fun1 and is now 100
'x' is not local to fun anymore and returns to it's original value:  10
'x' is global and is 10
'x' is global and is now 100
'x' is not local to fun2 but since fun2 uses global 'x' value is now: 100

啊,这个问题的最高答案澄清了我的困惑。谢谢。我不是问如何改变它,只是问为什么它不会改变。“可能重复”的答案解释了这一点。
'x' is  10
'x' is still 10
'x' is local to fun1 and is 10
'x' is local to fun1 and is now 100
'x' is not local to fun anymore and returns to it's original value:  10
'x' is global and is 10
'x' is global and is now 100
'x' is not local to fun2 but since fun2 uses global 'x' value is now: 100