全局范围变量在python中不变 [英] Global scope variable unchanging in python

查看:40
本文介绍了全局范围变量在python中不变的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这段代码中

money = .3事情 = [没什么"]定义主():打印去买东西"打印 "Current Money %s" % (money)打印你拥有的东西:"对于事物中的项目:打印项目等待 = raw_input()买东西(钱)定义购买(金钱):打印输入买买东西"购买 = raw_input()如果买==买":钱 = 钱 - .3Things.append("事物")主要的()别的:打印你什么都没买"打印 ""main()

为什么买完东西钱不下来?这对我来说已经有一段时间了,我似乎无法理解示波器在这种情况下是如何工作的.

解决方案

全局变量 moneybuythings(money) 中的函数参数 money 遮蔽 函数.您应该删除参数以使其工作:

def main():全球货币全球事物...定义购买():全球货币全球事物...

然而,正如 alfasin 指出的那样,更好的方法是传递 moneyThings 作为两个函数的参数并且根本不使用 global 关键字:

def main(money, things):...对于事物中的项目:打印项目等待 = raw_input()买东西(钱,东西)def 买东西(钱,东西):...如果买==买":钱 = 钱 - .3Things.append("事物")主要(金钱,事物)别的:...主要(金钱,事物)

<小时><预><代码>>>>钱 = .3>>>事情 = [没什么"]>>>主要(金钱,事物)

希望这会有所帮助.

In this code

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

Why after buying the things does the money not go down? This has been a problem to me for a while now and I cant seem to understand how the scope works in this situation.

解决方案

The global variable money is shadowed by the function parameter money in buythings(money) function. You should remove the parameter for it to work:

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

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

However, A better approach, as alfasin pointed out, would be passing money and Things as parameters to both functions and not using global keyword at all:

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)

Hope this helps.

这篇关于全局范围变量在python中不变的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆