Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Incrementing integer variable of global scope in Python [duplicate]

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?

like image 935
Pip S Avatar asked Jun 21 '15 12:06

Pip S


People also ask

Can we increment a global variable?

You can use $INCREMENT on a global variable or a subscript node of a global variable.

How do you increment a global variable inside a function in Python?

Example 3: Changing Global Variable From Inside a Function using global. In the above program, we define c as a global keyword inside the add() function. Then, we increment the variable c by 2, i.e c = c + 2 . After that, we call the add() function.

Can you increment with ++ in Python?

If you are familiar with other programming languages, such as C++ or Javascript, you may find yourself looking for an increment operator. This operator typically is written as a++ , where the value of a is increased by 1. In Python, however, this operator doesn't exist.


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

like image 168
Martijn Pieters Avatar answered Oct 16 '22 16:10

Martijn Pieters