0
def add():
    x = 15
    def change():
        global x
        x = 20
    print("Before making change:", x) #15
    print("Making change ---")
    change()
    print("After making change:", x) #15 hmm why?

add()
print("Value of x:", x) #20

My question is why the value of x after making change still 15 since i think the global x in change() would alternate the value of x to 20. An insight into the mix nature of call by reference + call by value of Python would be highly appreciated.

Jung
  • 139
  • 6
  • 1
    Cause `x` which is `15` is local variable of `add` function. `global x` defines a global variable if it wasnt defined before. – sashaaero Oct 03 '19 at 10:57
  • 1
    `global` actually means *global* in Python, not "somewhere other than local". – deceze Oct 03 '19 at 10:59

1 Answers1

-2

Your first x is not the global x, try adding a global x before the first x.

LeoE
  • 2,054
  • 1
  • 11
  • 29
  • Can someone let me know, why this answer is being downvoted? I tested it and with adding `global x` before the first x it works. Since the asker already uses the global keyword I assumed, this is fine with the rest of the code. I did not know about nonlocal and it is probably better, but my answer is not wrong, is it? Really want to know – LeoE Oct 03 '19 at 14:02
  • Because the apparent goal is to use the `x` that is already local to `add`, as a local, not to create a global variable. Anyway, this question is a common duplicate. – Karl Knechtel Sep 11 '22 at 09:53