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