0

I'm doing a homework assignment for my CompSci class and this question came up:

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

When running this, the value that is printed out is 36, but when a run print(x), x is still 6.

I would like to know why this happens; why x does not change?

Thanks!

BryanLavinParmenter
  • 416
  • 1
  • 8
  • 20

3 Answers3

1

That's because 'global x' is different than 'fun x', 'fun x' overlaps/masks the 'global x', does whatever you do with it and then it ceases to exist. The mask is not there so former 'global x' is again the current 'x'.

As stated you can overcome this by using 'global x' inside the function, note the difference between fun1 and 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

output:

'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
f.rodrigues
  • 3,499
  • 6
  • 26
  • 62
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()
Jeff Ferland
  • 17,832
  • 7
  • 46
  • 76
0

if you want to modify global variable in function use global keyword:

global x

otherwise local variable will be created during assignment.

ISanych
  • 21,590
  • 4
  • 32
  • 52