0

I have written a simple function to understand local and global scope in Python .

x = 50


def func(x):
    print('x is', x)
    x = 2
    print('Changed local x to', x)


func(x)
print('x is still', x)

what I want to understand here is inside the function during x= 2 assignment whether any new variable is getting created as the globally the variable x is still holding the value 50 . How this process occurs in Python?

k roy
  • 11
  • 1
  • 2
    `x` inside the function is a completely different variable from `x` outside the function. – khelwood Sep 12 '17 at 12:57
  • Interesting, the exact same code and a very similar question. Is this an assignment or part of a book? – MSeifert Sep 12 '17 at 13:01
  • @khelwood carefull! he his giving the function (via argument) a reference to the global `x`. The reason the global `x` is still holding 50 is because integers are not mutable... if you used `[50]` instead you could manipulate the global state from inside the function... – Chris Sep 12 '17 at 13:01
  • 1
    @Chris It's the same object but a different variable (https://nedbatchelder.com/text/names.html) it just happens to have the same variable name which (possibly intentional) complicates understanding. – MSeifert Sep 12 '17 at 13:03
  • @khelwood True... my point was just that different variables can point to the same object... and if that object is mutable, manipulations inside the function body can cause side-effects. – Chris Sep 12 '17 at 13:07

1 Answers1

0

Yes, a new variable is created. Python's scoping rules mean that variables of the same name in different scopes are unrelated - variable references are always to the innermost scope containing a variable with that name unless this is overridden with a global statement.