我是Python的新手,我从未学过任何其他编程语言。我似乎得到了这个错误,我已经阅读了其他帖子,但他们说在[dollar = 0]之前放置全局,这会产生语法错误,因为它不允许[= 0]。我正在使用[美元]作为计数器,所以我可以跟踪我添加到它的内容并在需要时将其显示回来。有人能帮助我吗?感谢。
<>代码<>
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()
&LT;&GT;回溯&LT;&GT;
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
答案 0 :(得分:19)
您需要添加global dollars
,如下所示
def search():
global dollars
print('You gain 5 bucks')
dollars = dollars + 5
shop()
每次你想要在函数内部更改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.')
当你购买东西时,你还需要减少美元!
P.S - 我希望你使用的是Python 3,你需要使用raw_input
代替。
答案 1 :(得分:2)
您需要将global dollars
放在一条线上,在您更改美元值的任何函数内。在您显示的代码中仅显示search()
,但我假设您还希望在shop()
内执行此操作以减去您购买的商品的价值...