[Tutor] variable existence q
Peter Otten
__peter__ at web.de
Sun Aug 16 11:10:20 CEST 2015
Clayton Kirkwood wrote:
>> > Above is the actual code.
Clayton, try to understand how scoping works in Python before you go back to
your actual code. Can you predict what the following snippet will produce?
x = "first global"
def f():
return x
def g():
return x
x = "local"
x = "second global"
print(f())
print(g())
What will the first print() produce?
'first global', i. e. the value the name x is bound to when f is created, or
'second global', the value the name x is bound to when f() is invoked?
What will g() try to return? The local variable x or the global variable x?
Does it succeed? If not, why?
Once you are clear about both problems fixing your actual code should be
easy.
More information about the Tutor
mailing list