Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #53008 > unrolled thread

Re: Python Global variable

Started byMRAB <python@mrabarnett.plus.com>
First post2013-08-26 17:18 +0100
Last post2013-08-26 17:18 +0100
Articles 1 — 1 participant

Back to article view | Back to comp.lang.python

This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by below is the oldest one visible, not the original post.


Contents

  Re: Python Global variable MRAB <python@mrabarnett.plus.com> - 2013-08-26 17:18 +0100

#53008 — Re: Python Global variable

FromMRAB <python@mrabarnett.plus.com>
Date2013-08-26 17:18 +0100
SubjectRe: Python Global variable
Message-ID<mailman.241.1377533929.19984.python-list@python.org>
On 26/08/2013 10:54, chandan kumar 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.
>
In a function, if you bind to a name then Python assumes that the name
is local to that function unless you declare that it's global.

In test1, you refer to 'CHK' but don't bind to it, therefore it's
global.

In test2, you bind to 'CHK' with 'CHK=40', and you haven't declared
that it's global, therefore it's local to test2.

In test3, you declare that 'CHK' is global, but don't mention it
anywhere else in that function, so it serves no purpose.

[toc] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web