Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/331.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 为什么可以';我不能从函数内部更改全局变量吗?_Python_Python 3.x - Fatal编程技术网

Python 为什么可以';我不能从函数内部更改全局变量吗?

Python 为什么可以';我不能从函数内部更改全局变量吗?,python,python-3.x,Python,Python 3.x,这是我的密码: def displayInventory (): print ("Inventory: " + str(inventory)) def enterEcdysis(): global xcash xcash -= 1 displayInventory() xcash = 3 inventory = [str(xcash) + ' Cash',] enterEcdysis() 我试图打印这张['2 Cash',],但当我运行它时,它仍然显示为3

这是我的密码:

def displayInventory ():
    print ("Inventory: " + str(inventory))

def enterEcdysis():
    global xcash
    xcash -= 1
    displayInventory()

xcash = 3
inventory = [str(xcash) + ' Cash',] 
enterEcdysis()
我试图打印这张
['2 Cash',]
,但当我运行它时,它仍然显示为
3
。我不确定我到底做错了什么。
xcash-=1
是否应该从全局变量中去掉一个?

它正在更新
xcash
。问题是
库存
已过时。在调用
enterEcdysis()
之前,您将其设置为
['3 Cash']
,而在修改
xcash
之后,您不会对其进行更新

将打印语句更改为直接打印
xcash
,您将看到它工作正常:

def displayInventory ():
    print ("Inventory: {} Cash".format(xcash))
考虑上面的代码行。 您已经使用xcash的当前值创建并设置了可变库存,该值在调用肠蜕皮症之前为3。 在“肠蜕皮症”中,您已从xcash值中减去1,但可变库存保持不变。 因此,当您稍后显示可变库存的值时,在定义库存时(当xcash仍然等于3时),仍然会显示库存的值

如果您如上所述修改displayInventory,您将看到xcash的值确实发生了更改,但您没有更改inventory的值。

进一步说明:“inventory=[str(xcash)+‘Cash’,]”行只发生一次。它不会在“xcash”更改时自动更改“inventory”的内容。如果您想更改“库存”,则需要调用代码对其进行更新。
xcash = 3
inventory = [str(xcash) + ' Cash',] 
enterEcdysis()
def displayInventory ():
    print ("Inventory: " + str(inventory) + "\t" + str(xcash))