[Tutor] Equivalent of a Subroutine in Python?

David Porter jcm@bigskytel.com
Thu, 1 Feb 2001 17:55:58 -0700


* Seelinger, Bruce <bseelinger@neteffectcorp.com>:

> Another question from someone totally new to Python. Is there an equivalent
> in Python to a sub-routine, (e.g. gosub and return).  I want to create a
> modular program with sub-routines to perform distinct tasks wihin the
> program for organizational and debugging purposes, etc.  Is the only (or
> best) way to do this is with modules?  

What about functions?

According to http://foldoc.doc.ic.ac.uk/foldoc/foldoc.cgi?query=subroutine 

"A function is often very similar to a subroutine, the main difference
being that it is called chiefly for its return value, rather than for any
side effects."

> A function works but the values obtained within the function do not appear
> to be valid outside of that function.  

That is because they are local to the function's namespace. If you want them
to be global, then you must declare them so:

def fun():
    global x
    x = 11    

fun()    
print x


Or you could use a standard function with return value:

def fun2():
    return 11

x = fun2()
print x


David