Incrementing integer variable of global scope in Python [duplicate]

谁说我不能喝 提交于 2020-04-07 03:29:19

问题


I am trying to change global value x from within another functions scope as the following code shows,

x = 1
def add_one(x):
    x += 1

then I execute the sequence of statements on Python's interactive terminal as follows.

>>> x
1
>>> x += 1
>>> x
2
>>> add_one(x)
>>> x
2

Why is x still 2 and not 3?


回答1:


Because x is a local (all function arguments are), not a global, and integers are not mutable.

So x += 1 is the same as x = x + 1, producing a new integer object, and x is rebound to that.

You can mark x a global in the function:

def add_one():
    global x
    x += 1

There is no point in passing in x as an argument here.



来源:https://stackoverflow.com/questions/30964478/incrementing-integer-variable-of-global-scope-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!