Changing a variable created outside a function within a function using Python
Question: I am trying to change the value of player_score, cpu_score, and ties which
were created outside the function determineWinner but I get an error such as
this: UnboundLocalError: local variable 'cpu_score' referenced before
assignment. I have deleted the other assignments (player_score=player_score+1
and ties=ties+1) and added the print ("Player Score",player_score) to test the
program.

I don't understand is why print ("Player Score",player_score) outputs the
value assigned outside of the function but cpu_score=cpu_score+1 yields the
"referenced before assignment" error.

Also showRolls does what it is supposed to.

It seems that the functions can read the values of the variables assigned
outside of the functions but can not change the values. Why is that?

    
    
    import random
    
    def showRolls():
        print("Player 1 roll:",player_roll)
        print("CPU roll:",cpu_roll)
    
    def determineWinner():
        if player_roll > cpu_roll:
            print("Player wins!")
            print ("Player Score",player_score)
        elif cpu_roll > player_roll:
            print("CPU wins!")
            cpu_score=cpu_score+1
        else:
            print("It's a tie.")
    
    #-----------------------MAIN PROGRAM------------------------------------
    player_score=0
    cpu_score=0
    ties=0
    player_roll = random.randint(1,6)
    cpu_roll = random.randint(1,6)
    showRolls()
    determineWinner()
    


Answer: Within your function declare any variables that are external to your function,
and that you want to _change_ , as `global`. Reading a global variable does
not require the declaration. There is some explanation
[here](https://docs.python.org/2/faq/programming.html?highlight=global%20variable#what-
are-the-rules-for-local-and-global-variables-in-python).

So, your function should be:

    
    
    def determineWinner():
        global cpu_score
        if player_roll > cpu_roll:
            print("Player wins!")
            print ("Player Score",player_score)
        elif cpu_roll > player_roll:
            print("CPU wins!")
            cpu_score=cpu_score+1
        else:
            print("It's a tie.")
    

