Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python variable scope with only function

Tags:

python

I don't understand why this code prints None in b():

# coding: utf-8                                                                               


saber = None
rider = dict()


def a():
    saber = 'ex'
    rider['a'] = 'b' 
    print saber
    print rider


def b():
    print saber
    print rider


if __name__ == '__main__':
    a() 
    b() 

When b() is called, printing saber results in None being printed. Why?

like image 995
E_Jovi Avatar asked Nov 30 '22 10:11

E_Jovi


2 Answers

saber is None in b() because you have defined it as a global variable with a value of None and have not defined a local variable of the same name in that function. In a() you defined saber with a value of "ex" and when you printed that variable, that's what you got. But that value of saber went away when the function finished, because it is local to the function, and that's what local variables do.

Now you might ask why rider was changed in a() when saber was not. But in fact, rider was not changed. You did not assign to the name rider in a(), so the global variable rider was used. The contents of rider were changed (you added a new key/value pair) but rider itself is still the same dictionary object it was when you first defined it. And that's why when you print it in b() you get the changed dictionary. Both functions are using the global variable rider because there is no local variable of the same name "hiding" it.

like image 158
kindall Avatar answered Dec 06 '22 19:12

kindall


In a(), you are re-declaring saber locally, and so it references a local variable and not the global that you declared in the beginning of your code. See this documentation for more information. The solution is to declare saber global at the beginning of a():

def a():
    global saber
    saber = 'ex'
    rider['a'] = 'b' 
    print saber
    print rider
like image 39
michaelgulak Avatar answered Dec 06 '22 19:12

michaelgulak