If I understand correctly, You are trying to increment variable a
using function inc(var)
and passing 'a' as a external variable to the function inc()
.
As @Marko Andrijevic stated, variable x passed to function inc() and variable x defined in the function are different . One way to achieve is by returning value of x and collecting externally, which you may not be looking for.
Alternately, Since you have defined variable 'a' outside function ,it can be called global
variable.
If you want to pass that to a function, and manipulate it, you need to define that variable ('a' in your case) inside the function as global
. Something like below.
def inc(x):
global a
a = x+1
Now when the new value assigned to 'a' after 'x+1', it is retained after execution of 'inc(x)'
>>> a = 0
>>> inc(a)
>>> a
1
EDIT -1
As per comments by @DYZ . Its correct. declaring global a
inside inc()
function will always increment a.
A better alternative will be , in that case, to return x
inside inc()
and assign that value to any external variable.
Not an elegant solution, but works as intended.
def inc(x):
return x+1
Result
>>> a
0
>>> a = inc(a)
>>> a
1
>>> a = inc(a)
>>> a
2
>>> b = 0
>>> b = inc(b)
>>> b
1
>>> a
2
>>>