Search code examples
pythonscoping

Lexical Scoping in Python


I am learning Python and more specifically I am exploring the scoping rules.

I tried the following "experiment":

def increment(n): 
   n += 1 
   print(n)
   return n

n = 1 
increment(n) 
print(n) 

This piece of code outputs: 2 , 1. Should n't it output instead 2, 2 since the variable n is returned to the global environment?

Your advice will be appreciated.


Solution

  • You have two distinct variables (names) here: one lives in the global scope, the other is local to increment. Rebinding the local one in increment doesn't impact the global one, and the fact that increment returns it's own n has no impact on the global one either (the fact they have the same name is irrelevant). If you want to have the global n pointing to the value returned by increment(), you have to rebind it explicitely:

    n = 1
    print(n)
    n = increment(n)
    print(n)