UnBoundLocalError: Local Variable Referenced Before Assignment [Counter]
本问题已经有最佳答案,请猛点这里访问。
我对Python还不熟悉,而且我从未学过其他编程语言。我似乎得到了这个错误,我读过其他文章,但是他们说把global放在[dollars=0]之前,这会产生语法错误,因为它不允许使用[=0]。我使用[美元]作为计数器,这样我就可以跟踪添加到其中的内容,并在需要时显示出来。有人能帮我吗?谢谢。
<代码>
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | dollars = 0 def sol(): print('Search or Leave?') sol = input() if sol == 'Search': search() if sol == 'Leave': leave() def search(): print('You gain 5 bucks') dollars = dollars + 5 shop() def leave(): shop() def shop(): shop = input() if shop == 'Shortsword': if money < 4: print('I\'m sorry, but you don\'t have enough dollars to buy that item.') shop1() if money > 4: print('Item purchased!') print('You now have ' + dollars + ' dollars.') sol() |
<>追溯< >
1 2 3 4 5 6 7 8 | Traceback (most recent call last): File"C:/Users/justin/Python/Programs I Made/Current/Testing.py", line 29, in <module> 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: local variable 'dollars' referenced before assignment |
您需要添加
1 2 3 4 5 | def search(): global dollars print('You gain 5 bucks') dollars = dollars + 5 shop() |
每当您想在函数中更改一个
1 2 3 4 5 6 7 8 9 10 11 | 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.') |
当你买东西的时候,你还需要减少费用!
另外,我希望您使用的是python 3,您需要使用
你需要把