Can global variable be passed into Python function?
gary.herron at islandtraining.com
Fri Feb 21 09:41:59 CET 2014
On 02/20/2014 10:37 PM, Sam wrote:
> I need to pass a global variable into a python function. However, the global variable does not seem to be assigned after the function ends. Is it because parameters are not passed by reference? How can I get function parameters to be passed by reference in Python?
Are you passing a value *into* a function, or back *out of* the
function? These are two very different things, and your question
mentions both and seems to confuse them.
You can pass any value into a function through its parameters, whether
that value comes from a local variable, global variable, or the result
of some computation. (But consider: it is the value that is being passed
in -- not the variable that contains that value.) You can't pass values
back out from a function through assignment to any of the parameters.
The global statement is a way to allow a function to assign to a global
variable, but this would not be considered "passing" a global into a
function. It's just a way to access and assign to a global variable
from withing a function.
v = 123
global v # Now v refers to the global v
print(v) # Accesses and prints the global v
v = 456 # Assigns to the global v.
More information about the Python-list