I have the following code:
x = 1
def increaseX(number):
x += number
increaseX(2)
print(x)
I want to increase a glob variable via the function increaseX
, what is the best way to do this?
I have the following code:
x = 1
def increaseX(number):
x += number
increaseX(2)
print(x)
I want to increase a glob variable via the function increaseX
, what is the best way to do this?
I tried this and it works, but I don't feel this is the best way x = 1
def increaseX(number):
global x
x += number
increaseX(2)
print(x)
global
keyword is what you need:
x = 1
def increaseX(number):
global x
x += number
increaseX(2)
print(x)
Otherwise, Python tries to find x
in local namespace because of +=
(something like x = x + number
) and because in the right hand side of the assignment there is no x
defined, you will get :
UnboundLocalError: local variable 'x' referenced before assignment