2014-12-04 82 views
-1

我在做家庭作业我CompSci类和这个问题上来:Python为什么函数后变量不变?

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

运行此,即打印出来是36的值,但是当运行打印(X),X是仍然6.

我想知道为什么会发生这种情况;为什么x不改变?

谢谢!

+0

啊,对于这个问题,最多的回答清除了我的困惑。谢谢。 – BryanLavinParmenter 2014-12-04 00:25:09

回答

1

这是因为'全局x'与'有趣x'不同,'有趣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 
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() 
+0

我并没有问如何改变它,只是问为什么它没有改变。尽管“可能重复”答案解释了它。 – BryanLavinParmenter 2014-12-04 00:25:33

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

global x 

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

0

每个函数将其存储的变量在新的内存位置。因此,fun函数内的x与fun函数外的x不同。这就是为什么你必须要求它作为参数,并返回值。要检索值只需键入

X =乐趣(x)的

相关问题