Incrementing integer variable of global scope in Python [duplicate]
Asked Answered
R

1

7

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?

Revivify answered 21/6, 2015 at 12:26 Comment(2)
Because x is a local, not a global.Horrendous
You should read about scoping ... docs.python.org/2/reference/executionmodel.html #292478Glanti
H
7

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.

Horrendous answered 21/6, 2015 at 12:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.