Unnamed
Unnamed

Reputation: 15

I have a problem with Python global variables. Is this a bug or an error?

Please note that I am not an experienced programmer. This is the 2nd program I've written with global variables. The first wasn't even a real language

So I am making a game in python, running on Replit.com. Every time the last piece of code runs, I get an error.

UnboundLocalError: local variable 'playerExtraSoldiers' referenced before assignment.

Here is the link to the game, going into files>main.py is the code

playerExtraSoldiers is the problematic variable, which I have tried renaming, making sure every occurence was spelled right, etc. It uses this variable as part of a nested function. The function in which the variable is defined and labeled with "global" is both above it and runs prior to it.

The code where the varible is referenced. (line 175-182)

def playerGainSoldiers():
    playerExtraSoldiers+=100*len(playerCountries)
    if(ownsNorth==1):
        playerExtraSoldiers+=250
    if(ownsCentral==1):
        playerExtraSoldiers+=600
    if(ownsSouth==1):
        playerExtraSoldiers+=350

This is a piece of the very long function where I define a lot of variables. (line 92-96)

#Extra soldiers
global playerExtraSoldiers
playerExtraSoldiers=100
global opponentExtraSoldiers
opponentExtraSoldiers=100

I have tried the following to fix it, with no success: -remaning the variable, completely removing and rewritting every line it occurs on. -moving the part where it is defined -this worked at one point, by moving it into def playerGainSoldiers:, but it can't keep resetting to 100 because that ruins my game -not having the nested function

If for some reason line 93 looks like this the newest version isn't loaded yet, that was part of me testing solutions, and fixing it doesn't change anything

    #global playerExtraSoldiers

Upvotes: 1

Views: 437

Answers (1)

Benjamin Rio
Benjamin Rio

Reputation: 656

You should use the global keyword inside your method, to refer to the object defined in an outer scope.

Your code should look like this :

def playerGainSoldiers():
    global playerExtraSoldier
    playerExtraSoldiers+=100*len(playerCountries)
    if(ownsNorth==1):
        playerExtraSoldiers+=250
    if(ownsCentral==1):
        playerExtraSoldiers+=600
    if(ownsSouth==1):
        playerExtraSoldiers+=350

Upvotes: 1

Related Questions