0

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?

Baghdadi
  • 35
  • 3

2 Answers2

0

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)
Baghdadi
  • 35
  • 3
0

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

S.B
  • 13,077
  • 10
  • 22
  • 49