[Tutor] functions
Yann Le Du
yann@thphys.ox.ac.uk
Sun Dec 1 11:16:01 2002
> Exercise for the interested reader: What will this code print? Why?
>
> >>> d = 'foo'
> >>> def func():
> ... print d
> ... d = 'bar'
> ... print d
I thought this would print 'foo' then 'bar' but actually it just fails :
UnboundLocalError: local variable 'd' referenced before assignment
Apparently, it is the d='bar' assignment that conflicts with the print
d just above. This means that Python looks forward, understands that d is
local because of d='bar' , then goes back to print d and then says that
d is not yet defined ?
Y