I've started teaching myself python, and have noticed something strange to do with global variables and scope. When I run this:
x = 2
y = 3
z=17
def add_nums():
y = 6
return z+y
The result of 23 is printed... However, when I expand the return to be:
x = 2
y = 3
z=17
def add_nums():
y = 6
z = z + y
return z
I get the following error on line 6:
Local name referenced but not bound to a value.
A local name was used before it was created. You need to define the
method or variable before you try to use it.
I'm confused as why I am getting an error here, as z is global an accessible.
When a variable is on the left side of an equal sign python will create a local variable. When the variable is on the right side of the equal sign python will try to look for a local variable and if he can't find one then it will use a global variable. In your example, z is on the right and left side of the equal sign, to avoid ambiguities python raises an error. You need to use the global
syntax to avoid this:
x = 2
y = 3
z = 17
def add_nums():
global z
y = 6
z = z + y
return z