[Tutor] Organizing my code, should I use functions?

spir denis.spir at free.fr
Wed Apr 22 18:07:53 CEST 2009

Le Wed, 22 Apr 2009 08:49:22 -0600,
Eduardo Vieira <eduardo.susan at gmail.com> s'exprima ainsi:

> Hello! I’m not a programmer and am a beginner with Python, I would
> like suggestion about ways of tackling the task I had to do. I have
> bee been using the xlrd package to get data from some spreadsheets
> successfully.
> I have developed a simple report from a script that compares number of
> shipments recorded in 2 spreadsheets, with data from previous years
> and current year, respectively.
> Later on I was asked to include in the same report numbers from
> another branch of our company. So, basically all the code logic was
> the same, only two different files needed to be processed, and I
> wondered how would I save time avoiding repeating code, creating extra
> variables, etc. So, I simply decided to alter the code as little as
> possible and use the import statement. It's working this way. Sounds
> wise?

Functions are basically for two goals:
* To structure your code according to the logic you have in mind and/or organise it for practicle and clarity reasons.
* To *define* and name a block of code intended to be run later, through a call, possibly several times, especially when it gains flexibility with parameters.
The first purpose is always good. The second one meets yours needs: to make your code able to process data from any spreadsheet.
Even when importing a module (which is rather intended for higher level organisation), you still should use funcs inside the processing part of the program.

> I thought if I converted it to a function or a class would make
> it more flexible, but my understanding of classes are too basic yet,
> and am not sure if it's worth using it.

I guess classes are not really necessary here...

> I have noticed that in lot's of python code example, people make
> functions out of everything. I'm still too much attached to
> procedural, not functional programming, if I understand the terms
> correctly. I would appreciate any suggestions.

... but behind misleading names functions are precisely the main structuring tool for procedural programming. [The distinction between procedural & functional paradigms is based on other traits and rather related to the math. sense of 'function'.] 'Functions' in python simply are named blocks of code, possibly with parameters, that perform an action and/or return a result. [They are also a kind of object but this is another story.]

la vita e estrany

More information about the Tutor mailing list