Local and Global Names

Consider the following code:

	x = 5
	
	def f():
	    x = 9
	    print "Within f: x =", x
	
	print "Before f: x =", x
	f()
	print "After f: x =", x
	x = 5
	
	def f():
	    print "Within f: x =", x
	    x = 9
	    print "Within f: x =", x
	
	print "Before f: x =", x
	f()
	print "After f: x =", x
	x = 5
	
	def f():
	    print "Within f: x =", x
	    y = 9
	    print "Within f: y =", y
	
	print "Before f: x =", x
	f()
	print "After f: x =", x
	# print "After f: y =", y  # generates an exception
	x = 5
	
	def f():
	    global x
	    print "Within f: x =", x
	    x = 9
	    print "Within f: x =", x
	
	print "Before f: x =", x
	f()
	print "After f: x =", x

Namespaces

How Python looks up a name