Why Don't Return?

Tim Chase python.list at tim.thechases.com
Mon Dec 3 15:13:56 EST 2007


> Here is sample function:
> 
> def a():
>   b()
>   print c
> 
> def b():
>   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