Why Don't Return?

Jeff jeffober at gmail.com
Mon Dec 3 15:25:21 EST 2007


On Dec 3, 3:13 pm, Tim Chase <python.l... at tim.thechases.com> wrote:
> > Here is sample function:
>
> > def a():
> >   b()
b() is not being assigned to anything.  Use c = b() to have c assigned
in the local scope.
> >   print c
>
> > def b():
When you enter the function b, you are creating a new local scope.  c
disappears once the function returns.  The value of c is returned,
however, so if you assign a variable to b(), the value of c will be
available.  If you require assignment in the global scope, you *must*
use the global keyword.  That is bad practice, though.
> >   c = "Hi"
> >   return c
>
> > if __name__ == "__main__":
> >   a()
>
> > then run a(). Throws error about c not being defined. How do I return c from
> > b?
>
> you *do* return c from b, and within the scope of a(), c is not
> defined (within scope) as the error informs you.
>
> However when you call b(), you don't do anything with its return
> value.  Try
>
>    def a():
>      result = b()  # do something with the returned value
>      print result
>
> yes, there's also a "global" keyword, but it uglifies code and
> logic-flow horribily.
>
> -tkc




More information about the Python-list mailing list