python – Adding +1 to a variable inside a function

python – Adding +1 to a variable inside a function

points is not within the functions 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

python – Adding +1 to a variable inside a function

Move points into test:

def test():
    points = 0
    addpoint = raw_input (type add to add a point)
    ...

or use global statement, but it is bad practice.
But better way it move points to parameters:

def test(points=0):
    addpoint = raw_input (type add to add a point)
    ...

Leave a Reply

Your email address will not be published.