Python为什么函数后没有变量变化?

时间:2014-12-04 00:21:31

标签: python

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

x = 6
def fun(x):
    y = x**2
    x = y
    return(x)
fun(x)

运行时,打印出的值为36,但是当运行打印(x)时,x仍为6。

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

谢谢!

3 个答案:

答案 0 :(得分:1)

那是因为'全球x'不同于有趣的x','有趣的x'重叠/掩盖全局x',无论你用它做什么,它就不再存在了。面具不存在,所以以前的全球x'再次是当前的'。'。

如上所述,您可以通过使用全球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

答案 1 :(得分:0)

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

OR

x = 6
def fun():
    # generally bad practice here
    global x
    y = x**2
    x = y
fun()

答案 2 :(得分:0)

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

global x

否则将在赋值期间创建局部变量。