UnBoundLocalError:在分配之前引用的局部变量[Counter]

Jus*_*tin 7 python

我是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()
Run Code Online (Sandbox Code Playgroud)

<>回溯<>

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
Run Code Online (Sandbox Code Playgroud)

Suk*_*lra 21

您需要添加global dollars,如下所示

def search():
    global dollars
    print('You gain 5 bucks')
    dollars = dollars + 5
    shop()
Run Code Online (Sandbox Code Playgroud)

每次想要更改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.')
Run Code Online (Sandbox Code Playgroud)

当你购买东西时,你还需要减少美元!

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

  • Noo,不要修补它!我正在利用我的千言万语! (2认同)