I'm guessing by subprogram you mean function?
The reason you are getting a 1 instead of a 4 is because x = 1
sets a global variable (in the global scope).
When you do x = 4
inside of a function it creates a local variable (in that function's local scope). Once the function is finished, the local variables are discarded.
When you call b()
and it tries to look up the value of x, there is no local variable x (in b's local scope) so it uses the global variable x, which is 1.
If you want a()
to modify the global variable x, you have to options:
1) You can just modify the global variable explicitly
def a():
global x
x = 4
2) You can return the local varaible and assign it to the global (preferred)
def a():
x = 4
return x
x = a()