2

I'm new in python trying to execute this code:

def dubleIncrement():
    j = j+2

def increment():
    i = i+1
    dubleIncrement()

if __name__ == "__main__":

    i = 0
    j = 0
    increment()
    print i
    print j

But getting this error :

unboundlocalerror local variable 'i' referenced before assignment

Anybody has any idea why i is not global

imSonuGupta
  • 865
  • 1
  • 8
  • 17

1 Answers1

4

Declare global keyword inside your functions to access the global as opposed to local variable. i.e.

def dubleIncrement():
    global j
    j = j+2

def increment():
    global i
    i = i+1

Note that when you declare i = 0 and j = 0 in your if statement, this is setting a global variable, but since it is outside the scope of any functions, the global keyword is not necessary to use here.

Ideally, you should try to stay away from using global variables as much as possible and try to pass variables as parameters to functions (think about what happens when you decide to use the variable names i and j again in some other function-- ugly collisions could occur!). The following would be one much safer way to write your code:

def dubleIncrement(x):
    x = x+2
    return x

def increment(x):
    x = x+1
    return x

if __name__ == "__main__":
    i = 0
    j = 0
    i = increment(i)
    j = dubleIncrement(j)
    print i
    print j
kdawg
  • 153
  • 4