Variable scope in python

Hi, I started Python guided path course. In the variable scope section I face an issue.

In the notes we have a code snippet like this

x = "Global Variable" 
def foo(): 
    print("Value of x: ", x) 
foo()

I run it and change the value of variable x here is the code snippet:

x = "Global Variable"
def foo():
    x = "somthig new happen"
    print("Value of x: ", x)
foo()

it work fine without throw any exception it means, we can update the global variable value.
please correct me what I'm missing in understanding the concept.

thanks

Hi, you don’t actually update the global variable. Inside your foo function, you create a brand new x storage. When you have two variables with the same name, one inside a global scope or outer scope in your example it is x = “Global Variable” and one which is inside a function scope or block scope in your example it is x = “something new happen”, this is call a “Variable shadowing”. It’s look like an illusion. You create a global variable x and then you think that i use the same storage inside foo function that i created before, but it is not true. You can try this code snippet.

x = "Global Variable"

def foo():
    x = "Something happen"
    print(id(x))
    print("Value of x: ", x)

print(id(x))
foo()
print(x)

If you really want to change the value of global variable, then you need to do something like this…

x = "Global Variable"

def foo():
    global x
    x = "Something happen"
    print("Value of x inside foo: ", x)

foo()
print("Value of x inside globale : ", x)
1 Like