Confused: Newbie Function Calls
EW
ericwoodworth at gmail.com
Wed Aug 11 12:39:19 EDT 2010
This will work:
------------------------------------------------------------------------
sample_string=""
def gen_header(sample_string=""):
HEADER = """
mymultilinestringhere
"""
sample_string+= HEADER
return sample_string
def gen_nia(sample_string=""):
NIA = """
anothermultilinestringhere
"""
sample_string += NIA
return sample_string
sample_string = gen_header(sample_string)
sample_string = gen_nia(sample_string)
print(sample_string)
------------------------------------------------------------------------
and this will work
------------------------------------------------------------------------
sample_string=""
def gen_header(OtherString):
global sample_string
HEADER = """
mymultilinestringhere
"""
sample_string+= HEADER
def gen_nia(OtherString):
global sample_string
NIA = """
anothermultilinestringhere
"""
sample_string += NIA
gen_header(sample_string)
gen_nia(sample_string)
print(sample_string)
------------------------------------------------------------------------
The first one is the better of the 2 in this example but the second
one will show you how to use global variables if you really need to
use them
So your problem was that you thought you were working on a global
variable in your functions when you were not. Since the your def
lines contained sample_string that make it a local variable. So when
you were doing your += statements you were working on a local variable
and not a global variable. You were returning the value of the local
variable but you didn't have anything in the main body of your script
catching that value. So simply changing these 2 lines:
sample_string = gen_header(sample_string)
sample_string = gen_nia(sample_string)
made the global sample_string variable store the values of the return
data.
If you want to use global variables then you just have to do 2
things. First you have to make sure you don't have any local
variables it the function with the same name. So I change the name to
OtherString in the def line. Then you need a global statement at the
start of your function (global sample_string) that tells python that
you really do want to use that global variable.
Global variables can cause you no end of heartache so python forces
you to explicitly state that you want to use them.
Hope that helps.
More information about the Python-list
mailing list