Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding +1 to a variable inside a function [duplicate]

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!

like image 967
Errno Avatar asked Sep 19 '13 11:09

Errno


2 Answers

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
like image 80
user2722968 Avatar answered Sep 19 '22 12:09

user2722968


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
like image 20
Xeun Avatar answered Sep 20 '22 12:09

Xeun