There aren't any global variables in use here.
In the first example, z
is a parameter to the function, not a global. Note that when you increment z
, it does not change in the calling scope, because the z
inside the function is a copy of the z
you passed in from outside the function.
In the second example, there is no b
inside the function (the parameter is z
), which is why you get an error inside the function when you try to modify it.
To do what you're trying to do, you should make the parameter a mutable object that contains the value you're trying to mutate; that way you can modify the value inside the function and the caller will have access to the new value. You could define a class for this purpose, or you could simply make it a single-element list:
def a(z):
z[0] += 1
b = [5]
a(b) # b == [6]
Or, if possible, a better approach IMO is not to depend on mutability, and to just return the new value, requiring the caller to explicitly re-assign it within its scope:
def a(z)
return z + 1
b = 5
b = a(b) # b == 6