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

Hi, actually there is a property of python while compiling the code. When you declare the variable globally as well as with the same variable name inside a local scope i.e. within a function, method or if-else statement and you call that variable inside the local scope itself then what happens is while calling the variable the compiler checks for the variable inside the local scope first and then if that variable is not found within local scope then only it proceeds to global scope for that particular variable