When Python sees this assignment to coin_toss as it compiles the
toss_winner() function, it marks coin_toss as a local variable and
will not consult global scope when looking it up at runtime (this is
an implementation optimization that leaks into the language level).
Hence, when the function is executed, Python does a fast lookup of
coin_toss in the local scope, finds it has not been assigned to, and
raises the error you're seeing, not falling back to and examining the
global variable scope.
To fix the problem, rename the variable so its name differs from that
of the coin_toss() function. That way, Python won't optimize the
lookup and will consult the global scope when it goes to resolve
coin_toss() in toss_winner().
Cheers,
Chris
--
http://blog.rebertia.com
<OP>
As an additional note: in Python, everything is an object - including
modules, classes, and, yes, functions -, so there's no distinct
namespace for functions or classes. If you try to execute the "coin_toss
= coin_toss()" statement at the top level (or declare name 'coin_toss'
global prior using it in the toss_winner function), you wouldn't get an
UnboundLocalError, but after the very first execution of the statement
you would probably get a TypeError on subsquent attempts to call coin_toss:
>>> def coin_toss():
... print "coin_toss called"
... return 42
...
>>> coin_toss
<function coin_toss at 0x952517c>
>>> coin_toss = coin_toss()
coin_toss called
>>> coin_toss
42
>>> coin_toss()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not callable
>>>
</OP>
HTH