10

我收到此错误,并且我已阅读其他帖子,但他们说放在global前面dollars = 0会产生语法错误,因为它不允许= 0. 我将dollars其用作计数器,因此我可以跟踪添加到其中的内容并在需要时将其显示回来。

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()

错误信息:

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
4

2 回答 2

24

您需要添加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.')

当您购物时,您还需要减少美元!

PS - 我希望你使用的是 Python 3,你需要使用它raw_input

于 2013-07-08T07:56:49.860 回答
2

您需要global dollars在任何更改美元值的函数中单独放置一行。在您显示的代码中,只有 in search(),尽管我假设您也想在里面做它shop()以减去您购买的物品的价值......

于 2013-07-08T07:52:49.523 回答