Search code examples
pythonvariables

Making a score value that counts up instead of resetting back to zero


I am working on a Python program. I have the following code:

def AIScoreIncreaseParameter(parameter):
    return parameter+ 1

def AIScoreIncrease():
    scoreBoardAI=0
    print(scoreBoardAI)
    scoreBoardAI=AIScoreIncreaseParameter(scoreBoardAI)
    print(scoreBoardAI)

AIScoreIncrease()
AIScoreIncrease()

This is a snippet of a larger set of code I am using for a scoreboard for a game of rock paper scissors. I can't figure out how to have a non-global variable for a scoreboard score that counts up each time a function is called. This code just prints out (0101) when I want it to increase in value by one each time to (0102), but to define the variable I have to give it a value, which is zero. How can I fix this? I have run into this same issue another time and it severely limits the scope of the types of game recreations I can make as most games have a counting system that changes (score, currency, card values, etc.).


Solution

  • A good way to do this to avoid a global variable or globally-accessible name is with a local variable 'hidden' within a function closure.The code below shows an example of how this can be done:

    def get_next_num():
        num = 0
        started = False
        def inner_num():
            nonlocal  num, started
            if started:
                num += 1
            else:
                started = True
            return num
        return inner_num
    
    next_num = get_next_num()
    
    print(next_num())
    print(next_num())
    print(next_num())
    

    gives:

    0
    1
    2
    

    The code above ,could if required, be modified to allow a starting value (eg. other than 0) to be set by calling the function rather than 'hard coding' the value in the code. It would also be possible to rewrite the code as a function decorator which counts how many times some arbitrary function has been called.