Getting error "local variable referenced before assignment - how to fix?


I'm making a gambling program (i know this shouldn't be incredibly hard), and want to have multiple games which will be in subroutines. However, python seems to think my variables are being assigned in strange places.

I am semi-new to subroutines, and still have some issues here and there. Here is what I am working with:

# variables and subroutines
money = 500
losses = 0
wins = 0
wlr = (wins,':',losses)
egg = True

def fiftyfifty(bet):
    chance = random.randint(0,100)
    if chance > 50:
        losses += 1
        print('You lose!')
        money -= bet
        print('You now have ',money)
        wins += 1
        print('You win!')
        money += bet
        print('You now have ',money)

And here is how it is called:

elif gamechoice == 'fifty fifty':
        print('You have $',money,'\n')
        bet1 = money+1
        while bet1 > money:
            bet1 = int(input('How much do you want to bet?\n'))

I expect it to just go through, add a tally into win or loss, then update the money. However, I am getting this error: UnboundLocalError: local variable 'losses' referenced before assignment If I win, it says the same thing with local variable 'wins'.

As shown all variables are assigned at the top, then referenced below in subroutines. I am completely unsure on how python thinks I referenced it before assignment?

I would appreciate any help, thank you in advance!


The reason is that losses is defined as a global variable. Within functions (local scope), you can, loosely speaking, read from global variables but not modify them.

This will work:

losses = 0

def f():


This won't:

losses = 0

def f():
    losses += 1


You should assign to your variables within your function body if you want them to have local scope. If you explicitly want to modify global variables, you need to declare them with, for example, global losses in your function body.

Collected from the Internet

Please contact javaer1[email protected] to delete if infringement.

edited at


Login to comment