Python Global variable

Joel Goldstick joel.goldstick at gmail.com
Mon Aug 26 12:10:43 EDT 2013


On Mon, Aug 26, 2013 at 5:54 AM, chandan kumar <chandan_psr at yahoo.co.in> wrote:
> Hi all,
>
> Please see the below code,in which i'm verifying the global value in python.
>
> CHK=10
>
> def test1():
>     print "Value of  CHK in test1",CHK
>
> def test2():
>     CHK=40
>     print "Value of CHK  in test2",CHK
>     test1()
>
> def test3():
>     global CHK
>     test2()
>
> test3()
>
> When i ran above code ,I'm getting vlaue of CHK as 40 in test2 method and 10 in test1 method
> Can somone explain me why the value of CHK  is different in method test1 and test2.

First, you are using incorrect terminology.  You are defining
functions here, not methods.  A method is a 'function' that is
contained within a class.

Now, on to your question.

You define CHK = 10 at the top of your code.  CHK is a name defined
within the global namespace of your file.

In test1 you print CHK which will be the value of the global CHK.
This is because, in python if a referenced name isn't present in the
most immediate namespace (test1), it will look in the successive
containing namespaces. to find the value.

In test2 you create a new name CHK which is not the same as the outer
CHK.  The test2 CHK is only visible within the function.  You assign
it the value 40.  When it executes, it prints 40.

In test3 you let test3 know that CHK refers to the global (outer) name
CHK.  However when you call test2, you do it with no parameters.
test2 knows nothing of your test3 internal names.

You need to look up python namespaces, and scoping.  I believe these
are covered in the python.org tutorial.  Be aware that if you learned
another language (C, Java) that names will confuse you for a while in
python.
>
> Best Regards,
> Chandan
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list



-- 
Joel Goldstick
http://joelgoldstick.com



More information about the Python-list mailing list