Reputation: 37
stored=0
def store(arg):
stored=arg
return stored
y=store(22)
print(y)
print(stored)
Output:
22
0
I really want to understand why print(stored)
is not equal to 22.Thank you so much.
Upvotes: 0
Views: 163
Reputation: 160377
Because the function isn't altering stored
that's located in the global scope. It is creating a local variable stored
inside the function, assigning a value to it and returning it. The assignment affects the local stored
, it doesn't touch the global stored
.
You can make it refer to the global stored
by using the global
statement:
def store(arg):
global stored
stored = arg
return stored
Adding the global <var_name>
statement tells Python that stored
is referring to a name that exists in the global scope; any assignments/modifications to stored
inside the function store
will now alter the corresponding name in the global scope.
Upvotes: 1