Procedures

J. Cliff Dyer jcd at sdf.lonestar.org
Mon Jun 22 16:03:31 EDT 2009


On Mon, 2009-06-22 at 12:13 -0700, Greg Reyna wrote:
> Learning Python (on a Mac), with the massive help of Mark Lutz's 
> excellent book, "Learning Python".
> 
> What I want to do is this:
> I've got a Class Object that begins with a def.  It's designed to be 
> fed a string that looks like this:
> 
> "scene 1, pnl 1, 3+8, pnl 2, 1+12, pnl 3, 12, pnl 4, 2+4,"
> 
> I'm parsing the string by finding the commas, and pulling out the 
> data between them.
> No problem so far (I think...)  The trouble is, there is a place 
> where code is repeated:
> 
> 1. Resetting the start & end position and finding the next comma in the string.
> 

Have you looked at the split() method on string objects.  It works kind
of like this:

>>> s = "scene 1, pnl 1, 3+8, pnl 2, 1+12, pnl 3, 12, pnl 4, 2+4,"
>>> s.split(",")
['scene 1', ' pnl 1', ' 3+8', ' pnl 2', ' 1+12', ' pnl 3', ' 12', ' pnl
4', ' 2+4', '']
>>> elements = s.split(",")
>>> elements
['scene 1', ' pnl 1', ' 3+8', ' pnl 2', ' 1+12', ' pnl 3', ' 12', ' pnl
4', ' 2+4', '']
>>> elements[2]
' 3+8'



> In my previous experience (with a non-OOP language), I could create a 
> 'procedure', which was a separate function.  With a call like: 
> var=CallProcedure(arg1,arg2) the flow control would go to the 
> procedure, run, then Return back to the main function.
> 

Python doesn't have procedures quite like this.  It has functions (the
things starting with "def"), which generally speaking take arguments and
return values.  For the most part, you do not want your functions to
operate on variables that aren't either defined in the function or
passed in as arguments.  That leads to difficult-to-debug code.  


> In Python, when I create a second def in the same file as the first 
> it receives a "undefined" error.  I can't figure out how to deal with 
> this.  How do I set it up to have my function #1 call my function #2, 
> and return?

Your problem description is confusing.  First of all, no class starts
with 'def'.  They all start with 'class'.  Perhaps you are talking about
a module (a python file)?  

Also, telling us that you get an undefined error is not particularly
helpful.  Every Exception that python raises is accompanied by an
extensive stack trace which will help you (or us) debug the problem.  If
you don't show us this information, we can't tell you what's going
wrong.  It will tell you (in ways that are crystal clear once you have a
bit of practice reading them) exactly what went wrong.

Can you show your code, as well as the complete error message you are
receiving?

My suggestions here, are essentially a paraphrasing of Eric Raymond's
essay, "How to Ask Smart Questions."  It is freely available on the web,
and easily found via google.  I recommend reading that, in order to get
the most mileage out this news group.

Cheers,
Cliff





More information about the Python-list mailing list