在函数中增加变量时出现"UnboundLocalError: local variable referenced before assignment"错误。
在函数中增加变量时出现"UnboundLocalError: local variable referenced before assignment"错误。
我遇到了这个错误,我已经阅读了其他帖子,但它们都说在 dollars = 0
之前加上 global
,但这会产生语法错误,因为它不允许 = 0
。我使用 dollars
作为计数器,这样我就可以跟踪我添加的内容,并在需要时显示出来。
错误信息:
Traceback (most recent call last):
File "C:/Users/justin/Python/Programs I Made/Current/Testing.py", line 29, in
sol()
File "C:/Users/justin/Python/Programs I Made/Current/Testing.py", line 7, in sol
search()
File "C:/Users/justin/Python/Programs I Made/Current/Testing.py", line 13, in search
dollars = dollars + 5
UnboundLocalError: 调用之前引用了本地变量 'dollars'
我得到了这个错误,我已经读了其他帖子,但他们说在 dollars = 0
前面加上 global
,但这导致语法错误,因为它不允许 = 0
。我使用 dollars
作为计数器,以便我可以跟踪我添加的内容,并在需要时显示出来。
当在函数中递增变量时,出现"UnboundLocalError: local variable referenced before assignment"的错误。解决方法是在函数中添加global dollars
语句来声明该变量为全局变量。以下是修复后的代码:
def search(): global dollars print('You gain 5 bucks') dollars = dollars + 5 shop()
每当你想要在函数中改变一个全局变量时,都需要添加这个global
语句。尽管在没有global
语句的情况下可以访问dollar
变量,但是在函数中对其进行修改时需要添加global
语句。
def shop(): global dollars shop = input("Enter something: ") if shop == 'Shortsword': if dollars < 4: # Were you looking for dollars? print('I\'m sorry, but you don\'t have enough dollars to buy that item.') shop1() if dollars > 4: print('Item purchased!') dollars -= someNumber # Change Number here print('You now have ' + dollars + ' dollars.')
在购物时,还需要减少dollars变量的值!注意,如果你使用的是Python 3,你需要使用raw_input
而不是input
。
修复后的代码应该可以正常运行。注意,由于你没有向input
传递任何参数,解释器会在一个空白屏幕上等待输入。你可以尝试修改代码:
Oh wow! I can't believe I missed that.. thank you!