question

Lie Lie.1296 at gmail.com
Tue Jun 3 08:39:01 EDT 2008


On May 30, 5:41 am, Gandalf <goldn... at gmail.com> wrote:
> On May 30, 12:14 am, John Henderson <jhenRemoveT... at talk21.com> wrote:
>
>
>
> > Gandalf wrote:
> > > how do i write this code in order for python to understand it
> > > and print me the x variable
>
> > > x=1
> > > def aaaa():
> > >     x++
> > >     if x > 1:
> > >         print "wrong"
> > >     else :
> > >         print x
>
> > > aaaa()
>
> > Example:
>
> > x=1
> > def aaaa(x):
> >     x += 1
> >     if x > 1:
> >         return "wrong"
> >     else :
> >        return x
>
> > print aaaa(x)
>
> > John
>
> mmm isn't their any global variable for functions?

the global keyword is only needed if you're going to write to the
variable, so this works:

glob = 1
def pp():
    print glob
pp()
print glob

while in:
glob = 1
def pp():
    glob = 2
    print glob
pp()
print glob

the 'glob' inside pp is different than the global 'glob'.

To use the global 'glob'
glob = 1
def pp():
    global glob
    glob = 2
    print glob
pp()
print glob

Using a global variable (whether with global keyword or not) is not a
very good thing to do as it makes codes hard to read as some have
already pointed out



More information about the Python-list mailing list