简体   繁体   中英

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)
        return
    else:
        wins += 1
        print('You win!')
        money += bet
        print('You now have ',money)
        return

And here is how it is called:

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

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():
    print(losses)

f()

This won't:

losses = 0

def f():
    losses += 1

f()

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.

The variables wins , money and losses were declared outside the scope of the fiftyfifty() function, so you cannot update them from inside the function unless you explicitly declare them as global variables like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM