z = 0 def calc0(): z = 10 print (locals()) def twice(): # UnboundLocalError: local variable 'z' referenced before assignment z *= 20 twice() return z + 10 def calc1(): z = 10 def twice(): global z z *= 20 twice() return z + 10 def calc2(): z = 10 def twice(): # UnboundLocalError: local variable 'z' referenced before assignment nonlocal z ## this is the fix z *= 20 twice() return z + 10 # print(calc0(10))