So basically I have no idea what is wrong with this small piece of code, and it seems like I can't find a way to make it work.
points = 0
def test():
addpoint = raw_input ("type ""add"" to add a point")
if addpoint == "add":
points = points + 1
else:
print "asd"
return;
test()
The error I get is:
UnboundLocalError: local variable 'points' referenced before assignment
Note: I can't place the "points = 0" inside the function, because I will repeat it many times, so it would always set the points back to 0 first. I am completely stuck, any help would be appreciated!
points
is not within the function's scope. You can grab a reference to the variable by using nonlocal:
points = 0
def test():
nonlocal points
points += 1
If points
inside test()
should refer to the outermost (module) scope, use global:
points = 0
def test():
global points
points += 1
You could also pass points to the function: Small example:
def test(points):
addpoint = raw_input ("type ""add"" to add a point")
if addpoint == "add":
points = points + 1
else:
print "asd"
return points;
if __name__ == '__main__':
points = 0
for i in range(10):
points = test(points)
print points
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With