fuglyducky wrote:
I am a complete newbie to Python (and programming in general) and I
have no idea what I'm missing. Below is a script that I am trying to
work with and I cannot get it to work. When I call the final print
function, nothing prints. However, if I print within the individual
functions, I get the appropriate printout.

Am I missing something??? Thanks in advance!!!!

################################################
# Global variable
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


gen_header(sample_string)
gen_nia(sample_string)

print(sample_string)
sample_string = gen_header(sample_string)
sample_string = gen_nia(sample_string)

print sample_string

That should work.

I guess you made an error thinking that

sample_string += HEADER

would change the value of the given parameter. It does not. The value is changed only for sample_string within the function This is the case for any immutable object (strings are immutable) in Python.

Example:


class AMutable(object):
   def __init__(self):
       self.description = 'I am X'

myString = 'I am a immutable string' # an immutable object
myMutable = AMutable() # a mutable object

def bar(myMutable):
myMutable.description = 'I am Y' # change the attribute description of the object

def foo(aString):
   aString = 'fooooooooo' # will have no effect outside the function

print 'before calling bar: ', myMutable.description
bar(myMutable)
print 'after calling bar: ', myMutable.description
print 'before calling foo: ', myString
foo(myString)
print 'after calling foo: ', myString


>
before calling bar:  I am X
after calling bar:  I am Y
before calling foo:  I am a immutable string
after calling foo:  I am a immutable string

cheers,

JM
--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to