unbundlocalerror:赋值前引用的局部变量[计数器]

2024-06-09 08:44:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我是Python新手,从未学过其他编程语言。我似乎得到了这个错误,我读过其他文章,但他们说把global放在[dollars=0]之前,这会产生语法错误,因为它不允许[=0]。我把[美元]当作一个计数器,这样我就可以跟踪我加在上面的东西,并在需要的时候显示出来。有人能帮我吗?谢谢。

<;gt;代码<;gt

    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

Tags: ltgtsearchifdefcurrentshopusers
2条回答

您需要将global dollars单独放在一行上,放在任何更改美元值的函数中。在您所展示的代码中,它只在search()中,尽管我假设您也希望在shop()中执行此操作,以减去您购买的商品的价值。。。

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

当你买东西的时候,你也需要减少美元!

我希望您使用的是Python3,您需要使用raw_input

相关问题 更多 >