问题描述
我正在制作一个赌博程序(我知道这应该不会太难),并且想要在子程序中拥有多个游戏.但是,python 似乎认为我的变量被分配在奇怪的地方.
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
这是它的名字:
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)
我希望它只是通过,在赢或输中添加一个计数,然后更新钱.但是,我收到此错误:UnboundLocalError:赋值前引用了局部变量'losses'
如果我赢了,它会用 局部变量 'wins'
说同样的话.
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'
.
如图所示,所有变量都在顶部分配,然后在下面的子程序中引用.我完全不确定 python 认为我在分配之前如何引用它?
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!
推荐答案
原因是 losses
被定义为一个全局变量.在函数(局部作用域)中,您可以松散地说,从全局变量中读取但不能修改它们.
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.
这会起作用:
losses = 0
def f():
print(losses)
f()
这不会:
losses = 0
def f():
losses += 1
f()
如果您希望变量具有局部作用域,则应该将它们分配给 函数体内的变量.如果您明确想要修改全局变量,则需要在函数体中使用例如 global loss
来声明它们.
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.
这篇关于获取错误“分配前引用的局部变量 - 如何解决?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!