TransWikia.com

why isn't my local variable overwriting the global?

Stack Overflow Asked by Pillow Study on December 7, 2021

The code that I’m running how come the local x isn’t overwriting the global x?

x = 'global x'

def test():
    global x
    x = 'local x'
    print(x)

print(x)
test()

Output:

global x

local x

4 Answers

The code that I'm running how come the local x isn't overwriting the global x?

The code of the function won't get executed until you call it. Here is the sequence of events in your script.

  1. Variable x is declared storing an object of type str having value global x.
  2. Interpreter parses the definition of the function test but doesn't execute it.
  3. You print the value of x using print.
  4. You call the function and it sets the global variable x to local x.

If you want to change the value of your variable x before printing. Do this:

x = 'global x'

def test():
    global x
    x = 'local x'
    print(x)

print("Value of x before test:", x)
test() 
print("Value of x after test:", x)

Outputs:

Value of x before test: global x
local x
Value of x after test: local x

Answered by abhiarora on December 7, 2021

Before the test function is called, x = 'global x' is no problem.

I think you wanna this

x = 'global x'

def test():
    global x
    x = 'local x'
    print(x)

print(x) # Before test call, x = 'global x'
test() # test called, x = 'local x'
print(x) # test called, x overwriting, x = 'local x'

Answered by K. Prot on December 7, 2021

I think it is. You're first printing x, which is the global x. Afterwards you're calling test which then prints the local x at the end of the function. Defining the function doesn't mean it gets called. If you want it to overwrite the global x with the nontest function, try

test()

print(x)

instead of

print(x)

test()

Answered by user3452643 on December 7, 2021

after the function call only it will replace the variable, swap the test and print(x) last two line, then you can see the magic

x = 'global x'

def test():
    global x
    x = 'local x'
    print(x)

test()
print(x)

Answered by Vignesh on December 7, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP