全局范围变量在python中不变

时间:2015-02-23 06:33:02

标签: python variables scope

在此代码中

money = .3

Things = ["Nothing"]

def main():
    print "go to buy things"
    print "Current Money %s" % (money)
    print "Things you have:"
    for item in Things:
        print item
    wait = raw_input()
    buythings(money)


def buythings(money):
    print "Type Buy to buy things"
    buy = raw_input()
    if buy == "buy":
        money = money - .3
        Things.append("Things")
        main()
    else:
        print "you bought nothing"
        print ""
        main()

为什么买东西后钱不会下降?这对我来说已经有一段时间了,我似乎无法理解范围在这种情况下是如何工作的。

2 个答案:

答案 0 :(得分:1)

全局变量moneymoney函数中的函数参数buythings(money)遮蔽。您应该删除它的参数:

def main():
    global money
    global Things
    ...

def buythings():
    global money
    global Things
    ...

然而,正如alfasin指出的那样,更好的方法是将moneyThings作为参数传递给两个函数,而不是使用global关键字:< / p>

def main(money, things):
    ...
    for item in things:
        print item
    wait = raw_input()
    buythings(money, things)


def buythings(money, things):
    ...
    if buy == "buy":
        money = money - .3
        Things.append("Things")
        main(money, things)
    else:
        ...
        main(money, things)

>>> money = .3
>>> Things = ["Nothing"]
>>> main(money, Things)

希望这有帮助。

答案 1 :(得分:0)

您可以在其他函数中使用全局变量,方法是在分配给它的每个函数中将其声明为全局变量:

money = 0

def set_money_to_one():
    global money    # Needed to modify global copy of money
    money = 1

def print_money():
    print money     # No need for global declaration to read value of money

set_money_to_one()
print_money()       # Prints 1

在你的情况下:

def buythings():
    global money
  Python希望确保你真正知道自己是什么   通过明确要求全局关键字来玩。