Incrementing integer variable of global scope in Python

This question already has an answer here:

  • How do I pass a variable by reference? 23 answers

  • 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.

    链接地址: http://www.djcxy.com/p/20828.html

    上一篇: Python和Java参数传递

    下一篇: 在Python中增加全局作用域的整数变量