Re: [Tutor] code structure terminology and advice

2009-07-22 Thread Alan Gauld


"Che M"  wrote 


You pretty much answered your own question.

The ultimate answer depends on a few other contextual issues.

Q1) Generally, what is the best structure for when there are 
a number of steps/actions that need to be taken?  


A sequence! :-)

Q2) Is there a term/some jargon in programming that 
refers to the difference between examples 1-3 below?


Not that I'm aware of.

 wish to perform four related sequential actions--steps, 
let's call them--in some part of the program.  


If the entire program consists of those 4 steps (as in a batch 
data processing program, say) then you might structure things 
differently than if the 4 steps are only part of a bigger 
program - one menu option out of several, say.


In the former you would perform the steps in sequence and 
may or may not put them in functions.depending on whether 
they would ever be reused and how long the code was per step.
In most cases the steps are likely to be reusable or of significant 
length so you would put each one in its own function.



1. Do the steps all in one function:

def Function(self):
  do step1 action
  do step2 action
  do step3 action 
  do step4 action


This would be sensible in the menu selection context.

2. Have each step be a function, and have each function 
call the next function in the chain:


No, this is terrrible from every point of view. It removes any 
opportunity of reuise of individual steps and builds up a deep 
call stack which makes debugging harder and the coupling 
between functions makes maintenance harder (for example 
swapping two steps around in the sequence)



def StepOne(self):
   do step1 action
   StepTwo()


3. Make each step a function, but call all of them in order in 
one master function:


def MasterFunction(self):
   self.StepOne()
   self.StepTwo()


This is just a variation on option 1 and the same applies.

The fourth option you do not consider but which could be the 
best solution for the batch program I discussed is just to perform 
each step from the top klevel of the program, ie no 
enclosing function


StepOne()
StepTwo()
StepThree()
StepFour()


It seems to me that example 3 is the most sensible.  


In general yes.

1 is bad because the steps should be functions, because then they 
can be easily reused, seen from an IDE explorer, etc. 
(I guess if they are really minor things it isn't necessary). 


This depends on the size of the steps and the nature of the overall 
programme, but functions would usually be best.


2 is terrible 


Yes.

Maybe there are other and better ways to think about organizing 
a sequence of steps, and if so I'd love to hear them.  


For longer and more complex processes you could use a table 
or list of functions and step through them in a loop


process = [StepOne, StepTwo,, stepN]

for step in process:
step()

Or for dynamically changing sequences you can create or hold 
a sequence list and use that to index a list of steps:


steps = [StepOne, StepTwo,, stepN]
sequence = [1,2,3,4]

def do Process(sequence)
   for step in sequence:
steps[step]()

This allows you to selectively peform some of the steps:

sequence = [1,3,4,N]

doProcess(sequence)

Finally for very complex scenarios you might implement a 
state machine where the return value of each step controls 
the next step in the sequence. That can be done by building 
a set of state objects or using a data driven approach with 
a table


You can read about state machines in several places, 
I'd start with Wikipedia.


You might also find that reading about business process execution
languages gives you some ideas about how to structure and 
represent complex processes. BEPL would be a good 
starting point, again try Wikipedia.


HTH,


--
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Question from a newbie

2009-07-22 Thread Glen Zangirolami
Deb,
For starters most of the Google enterprise runs on python.
Google App Engin e is for developers to
develop web applications on Google

There are many applications ranging from web frameworks to math modules.
Web frameworks: Django , Repoze
BFG,
Pylons , Turbo Gears ,
CherryPy 
NumPy  for math/physics.
Plone  is a content management system used by many
schools and governments.

Python website has lots of information to learn python.
Documents,
Python Enhancement Proposals ,
Communityand the Python
Package Index .

It is a beautiful language! Good Luck :)


On Tue, Jul 21, 2009 at 1:12 PM, Deb  wrote:

> My son suggested I play around with Python.  I was wondering if
> anybody has any real life applications?  It appears to be able to do quite a
> lot, but is anybody really doing it with Python?  I am very curious about
> this language.  I used to be a Clipper programmer in another life (dBASE
> compiler), and got sick when I was just entering the OOP world via Visual
> Basic and had to quit.  I just recently got my brain back, thanks to medical
> science, and would like to learn all I can about what it out there these
> days.
>
>  Thanks,
>
>
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
<><>___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] code structure terminology and advice

2009-07-22 Thread Glen Zangirolami
Che,

You should check out the python styling guide here.
It give examples about how to write python code.

PEP 8 -- Style Guide for Python Code

Hope this helps!
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Michael Knowles/NONFS/USDAFS is out of the office.

2009-07-22 Thread Michael Knowles

I will be out of the office starting  07/22/2009 and will not return until
07/27/2009.

I am out of the office and will respond to your message when I return on
Monday, 30 Sep.

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Question from a newbie

2009-07-22 Thread John
On Tuesday 21 July 2009 11:12:23 am Deb wrote:
> My son suggested I play around with Python.  I was wondering if anybody has
> any real life applications?  It appears to be able to do quite a lot, but
> is anybody really doing it with Python?  I am very curious about this
> language. I used to be a Clipper programmer in another life (dBASE
> compiler), and got sick when I was just entering the OOP world via Visual
> Basic and had to quit I just recently got my brain back, thanks to medical
> science, and would like to learn all I can about what it out there these
> days.
>
> Thanks,

Then you'll love Dabo (www.dabodev.com) which is built on python, wxPython, 
and supports databases like Postgres, MsSQL, MySQL, Firebird, and SQLite.  
The thinking is very similar to Visual FoxPro.  Classes are close and the 
coding is close.  If you ever used any of the VFP (clipper) frameworks then 
it will be old hat.


Johnf
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] demo/turtle

2009-07-22 Thread roberto
hello
i'd like to download the demo/turtle directory but i could not find
the correct link;

i need it to run the exampled cited in
http://docs.python.org/library/turtle.html

can you tell me where to find it ?
my version is 2.6.2

thank you very much
-- 
roberto
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] demo/turtle

2009-07-22 Thread Alan Gauld


"roberto"  wrote 


i'd like to download the demo/turtle directory but i could not find
the correct link;

i need it to run the exampled cited in
http://docs.python.org/library/turtle.html

can you tell me where to find it ?
my version is 2.6.2


I believe the new turtle module should be installed as standard on 2.6.
So the example code should just work.

Which OS are you on? Some Linux versions of Python 
don't have Tkinter loaded and that  will probably prevent 
turtle from running... 


What happens when you try it? Do you get an error message?


--
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] how to fill zero value and join two column

2009-07-22 Thread amrita

Hi,

I have two text file, having entries as
fileA
33 ALA H = 7.57 N = 121.52 CA = 55.58 HA = 3.89 C = 179.24
38 ALA H = 8.29 N = 120.62 CA = 54.33 HA = 4.04 C = 178.95
8 ALA H = 7.85  N = 123.95 CA = 54.67 HA =  C =
fileB
8 ALA  helix (helix_alpha, helix1)
21 ALA  helix (helix_alpha, helix2)
23 ALA  helix (helix_alpha, helix2)

now what i want that i will make another file in which the matching
entries from the two file get printed together along with zero values for 
those atoms which doesnot have nay value in fileA. so the reult will be
something like:-

fileC
8 ALA H = 7.85  N = 123.95 CA = 54.67 HA =0.00  C =0.00|8 ALA  helix
(helix_alpha, helix1)

I tried to merge these two files using commands like:-

from collections import defaultdict
>>> def merge(sources):
...   if __name__ == "__main__":
...a = open("/home/amrita/alachems/chem100.txt")
...c = open("/home/amrita/secstr/secstr100.txt")
...def source(stream):
...return (line.strip() for line in stream)
...for m in merge([source(x) for x in [a,c]]):
...print "|".join(c.ljust(10) for c in m)
...
but it is not giving any value.






Thanks,
Amrita Kumari
Research Fellow
IISER Mohali
Chandigarh
INDIA

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] code structure terminology and advice

2009-07-22 Thread Che M



> To: tutor@python.org
> From: alan.ga...@btinternet.com
> Date: Wed, 22 Jul 2009 08:46:04 +0100
> Subject: Re: [Tutor] code structure terminology and advice
> 
> 
> "Che M"  wrote 
> 
> You pretty much answered your own question.
> 
> The ultimate answer depends on a few other contextual issues.
> 
> > Q1) Generally, what is the best structure for when there are 
> > a number of steps/actions that need to be taken?  
> 
> A sequence! :-)
> 
> > Q2) Is there a term/some jargon in programming that 
> > refers to the difference between examples 1-3 below?
> 
> Not that I'm aware of.
> 
> >  wish to perform four related sequential actions--steps, 
> > let's call them--in some part of the program.  
> 
> If the entire program consists of those 4 steps (as in a batch 
> data processing program, say) then you might structure things 
> differently than if the 4 steps are only part of a bigger 
> program - one menu option out of several, say.
> 
> In the former you would perform the steps in sequence and 
> may or may not put them in functions.depending on whether 
> they would ever be reused and how long the code was per step.
> In most cases the steps are likely to be reusable or of significant 
> length so you would put each one in its own function.
> 
> > 1. Do the steps all in one function:
> > 
> > def Function(self):
> >   do step1 action
> >   do step2 action
> >   do step3 action 
> >   do step4 action
> 
> This would be sensible in the menu selection context.
> 
> > 2. Have each step be a function, and have each function 
> > call the next function in the chain:
> 
> No, this is terrrible from every point of view. It removes any 
> opportunity of reuise of individual steps and builds up a deep 
> call stack which makes debugging harder and the coupling 
> between functions makes maintenance harder (for example 
> swapping two steps around in the sequence)
> 
> > def StepOne(self):
> >do step1 action
> >StepTwo()
> 
> > 3. Make each step a function, but call all of them in order in 
> > one master function:
> > 
> > def MasterFunction(self):
> >self.StepOne()
> >self.StepTwo()
> 
> This is just a variation on option 1 and the same applies.
> 
> The fourth option you do not consider but which could be the 
> best solution for the batch program I discussed is just to perform 
> each step from the top klevel of the program, ie no 
> enclosing function
> 
> StepOne()
> StepTwo()
> StepThree()
> StepFour()
> 
> 
> > It seems to me that example 3 is the most sensible.  
> 
> In general yes.
> 
> > 1 is bad because the steps should be functions, because then they 
> > can be easily reused, seen from an IDE explorer, etc. 
> > (I guess if they are really minor things it isn't necessary). 
> 
> This depends on the size of the steps and the nature of the overall 
> programme, but functions would usually be best.
> 
> > 2 is terrible 
> 
> Yes.
> 
> > Maybe there are other and better ways to think about organizing 
> > a sequence of steps, and if so I'd love to hear them.  
> 
> For longer and more complex processes you could use a table 
> or list of functions and step through them in a loop
> 
> process = [StepOne, StepTwo,, stepN]
> 
> for step in process:
>  step()
> 
> Or for dynamically changing sequences you can create or hold 
> a sequence list and use that to index a list of steps:
> 
> steps = [StepOne, StepTwo,, stepN]
> sequence = [1,2,3,4]
> 
> def do Process(sequence)
> for step in sequence:
>  steps[step]()
> 
> This allows you to selectively peform some of the steps:
> 
> sequence = [1,3,4,N]
> 
> doProcess(sequence)
> 
> Finally for very complex scenarios you might implement a 
> state machine where the return value of each step controls 
> the next step in the sequence. That can be done by building 
> a set of state objects or using a data driven approach with 
> a table
> 
> You can read about state machines in several places, 
> I'd start with Wikipedia.
> 
> You might also find that reading about business process execution
> languages gives you some ideas about how to structure and 
> represent complex processes. BEPL would be a good 
> starting point, again try Wikipedia.
> 
> HTH,
> 
> 
> -- 
> Alan Gauld
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/

Thank you, Alan.  It is sometimes helpful just to get corroboration, and I feel 
that sometimes the simplest things are the most important.  I also thought that 
maybe the mistake in example 2 had a name; I don't know if it is a common 
mistake or not for beginning programmers, but I have found myself doing it 
sometimes and I am making a point to undo it now in any old code.  The point 
about looping through a list of functions is also something that hadn't 
occurred to me.  So this is all very helpful.

Thanks,
Che

_
Windows Live™ Hotmail®: Celebrate the moment with your favorite sports pics. 
Check it out.
http://w

Re: [Tutor] demo/turtle

2009-07-22 Thread roberto
On Wed, Jul 22, 2009 at 7:06 PM, Alan Gauld wrote:
>
> "roberto"  wrote
>>
>> i'd like to download the demo/turtle directory but i could not find
>> the correct link;
>>
>> i need it to run the exampled cited in
>> http://docs.python.org/library/turtle.html
>>
>> can you tell me where to find it ?
>> my version is 2.6.2
>
> I believe the new turtle module should be installed as standard on 2.6.
> So the example code should just work.
>
> Which OS are you on? Some Linux versions of Python don't have Tkinter loaded
> and that  will probably prevent turtle from running...
> What happens when you try it? Do you get an error message?
the os is Xp;
the problem is simply i cannot find this directory  in my current
python installation folder ...

>
>
> --



-- 
roberto
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] demo/turtle

2009-07-22 Thread Dave Angel

roberto wrote:

On Wed, Jul 22, 2009 at 7:06 PM, Alan Gauld wrote:
  

"roberto"  wrote


i'd like to download the demo/turtle directory but i could not find
the correct link;

i need it to run the exampled cited in
http://docs.python.org/library/turtle.html

can you tell me where to find it ?
my version is 2.6.2
  

I believe the new turtle module should be installed as standard on 2.6.
So the example code should just work.

Which OS are you on? Some Linux versions of Python don't have Tkinter loaded
and that  will probably prevent turtle from running...
What happens when you try it? Do you get an error message?


the os is Xp;
the problem is simply i cannot find this directory  in my current
python installation folder ...

  

According to:http://docs.python.org/library/turtle.html#demo-scripts,

the demo/turtle directory is in the *source* distribution.  Many Windows 
users don't get the source distro, they just get the windows install 
package.


Go to http://www.python.org/   and on the left side, find the link 
labeled  "source distribution"   Click on it, and you should be able to 
download   Python-2.6.2.tar.bz2  It's 10.6MB in size.
And inside that  tar.bz2 file, you'll find a directory  
Python-2.6.2\Demo\turtle


DaveA

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Bouncing mail

2009-07-22 Thread Dave Angel

Geneviève DIAGORN wrote:

Bonjour,
Je suis absente jusqu'au 23/07 inclus.
Je prendrai connaissance de votre mail vendredi.
En cas d'urgence Soprane, contacter Benoît Tottereau ou William Dibas.
Cordialement.

Geneviève 

  
If you must use an "out of office" auto-reply, then unsubscribe to the 
mailing list(s) first.  Getting all these French messages are pretty 
annoying, and I suspect it's going to anybody who posts to the list, not 
just to me.


Anyone else seeing these?

DaveA


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] xlwt & xlrd: can I refactor this code better?

2009-07-22 Thread Albert-Jan Roskam

Hi,

A while ago I wrote a program to merge xls files. Now I refactored it because 
before, it was one big chunk of spaghetti code and I wanted to add some 
functionality. The code below works, but I have the feeling that it could still 
be simplified. Most functions have many arguments - isn't that called 'tight 
coupling'? Could somebody give me a few general pointers as to how to improve 
this program without loosing functionality? The first function is the main() 
function. Shouldn't a programmer strive for information hiding in such a 
function? Ideally, it should almost read like regular english, right? Or is 
that too textbook-ish? ;-)

Thanks in advance!
Albert-Jan

"""
Merge all xls files in a given directory into one multisheet xls file.
The sheets get the orginal file name, without the extension.
File names should not exceed 29 characters
"""

import glob, os.path, time
import xlrd, xlwt

def merge_xls(in_dir="d:/temp/", out_file="d:/temp/merged_output.xls"):
""" Main function: merge xls sheets """
xls_files = glob.glob(in_dir + "*.xls")
xls_files.sort()
merged_book = xlwt.Workbook()
osheet_names = [os.path.basename(xls_file)[:-4] for xls_file in xls_files]
for xls_no, xls_file in enumerate(xls_files):
print "---> Processing file %s" % (xls_file)
book = xlrd.open_workbook(xls_file)
isheet_names = xlrd.Book.sheet_names(book)
check_xls(book, merged_book, isheet_names, osheet_names, xls_no, 
xls_files)
stamped_outfile = out_file[:-4] + "_" + time.strftime("%Y-%m-%d") + ".xls"
merged_book.save(stamped_outfile)
print_msg(xls_files, osheet_names, stamped_outfile)

def check_xls(book, merged_book, isheet_names, osheet_names, xls_no, xls_files):
""" Check existence and file names of input xls files """
if xls_files and len(osheet_names[xls_no]) <= 29:
write_sheets(book, merged_book, isheet_names, osheet_names, xls_no, 
xls_files)
elif xls_files:
print "WARNING *** File name too long: <%s.xls> (maximum is 31 chars) " 
% (osheet_names[xls_no])
print "WARNING *** File <%s.xls> was skipped." % (osheet_names[xls_no])
else:
print "NOTE *** No xls files in %s. Nothing to do" % (in_dir)

def write_sheets(book, merged_book, isheet_names, osheet_names, xls_no, 
xls_files):
""" Write sheets, and add sheet numbering in case of multisheet xls input 
"""
osheet_name = osheet_names[xls_no]
xls_file = xls_files[xls_no]
if book.nsheets == 1:
ws = merged_book.add_sheet(osheet_name)
isheet_name = isheet_names[0]
sheet = book.sheet_by_index(0)
write_cells(sheet, book, ws, isheet_name, osheet_name, xls_file)
elif book.nsheets in range(1, 100):
for sheetx in range(book.nsheets):
isheet_name = isheet_names[sheetx]
ws = merged_book.add_sheet(osheet_name+str(sheetx+1).zfill(2))
sheet = book.sheet_by_index(sheetx)
write_cells(sheet, book, ws, isheet_name, osheet_name, xls_file)

else:
raise Exception ("ERROR *** File %s has %s sheets (maximum is 99)" % 
(xls_file, book.nsheets))

def write_cells(sheet, book, ws, isheet_name, osheet_name, xls_file, 
format_cell=True):
""" Write cells, and apply formatting if needed """
MISSINGVALUES = ("#LEEG!", "#NULL!")
rx = 0 # initialize to zero in case of empty input xls file.
style = format_cells(ws)
for rx in range(sheet.nrows):
for cx in range(sheet.ncols):
cell_value = sheet.cell_value(rx, cx)
if format_cell and rx == 0:
format_cells(ws)
ws.write(rx, cx, cell_value, style)
elif cell_value in MISSINGVALUES or xlrd.XL_CELL_EMPTY: 
ws.write(rx, cx, "   ")
else:
ws.write(rx, cx, cell_value)
footer = "source tab: " + isheet_name + " || source file: " + 
os.path.basename(xls_file)
if format_cell:
ws.write(rx+2, 0, footer.upper(), style)  # print bold source tab & 
file name below the table
else:
ws.write(rx+2, 0, footer.upper())

def format_cells(ws, font='Arial', boldrow=True, panes_frozen=True):
""" Add horizontal split pane and bold font at first row """
ws.panes_frozen = panes_frozen
ws.horz_split_pos = 1
font0 = xlwt.Font()
font0.name = font
font0.struck_out = False
font0.bold = boldrow
style0 = xlwt.XFStyle()
style0.font = font0
return style0

def print_msg(xls_files, osheet_names, stamped_outfile):
""" Print status messages """
print "\n---> Merged xls file written to %s using the following source 
files: " % (stamped_outfile)
MAXSHEETNAMELEN = 29
for n_sheet, osheet_name in enumerate(osheet_names):
if len(osheet_name) <= MAXSHEETNAMELEN:
print "\t", str(n_sheet+1).zfill(3), "%s.xls" % (osheet_name)
excl_sheets = [os.path.basename(xls_file)[:-4] for xls_file in xls_files if 
\
   len

Re: [Tutor] Bouncing mail

2009-07-22 Thread Sander Sweers
2009/7/22 Dave Angel :
> Anyone else seeing these?

Unfortunately yes. Very annoying... :(

Greets
Sander
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] demo/turtle

2009-07-22 Thread Gregor Lingl



roberto schrieb:

On Wed, Jul 22, 2009 at 7:06 PM, Alan Gauld wrote:
  

"roberto"  wrote


i'd like to download the demo/turtle directory but i could not find
the correct link;

i need it to run the exampled cited in
http://docs.python.org/library/turtle.html

can you tell me where to find it ?
my version is 2.6.2
  

I believe the new turtle module should be installed as standard on 2.6.
So the example code should just work.

Which OS are you on? Some Linux versions of Python don't have Tkinter loaded
and that  will probably prevent turtle from running...
What happens when you try it? Do you get an error message?


the os is Xp;
the problem is simply i cannot find this directory  in my current
python installation folder ...
  
If you want only to download the demos (including the demoViewer) you 
can do it from here:


http://svn.python.org/view/python/trunk/Demo/turtle/

or if you use Python 3.1 from here (with two additional examples):

http://svn.python.org/view/python/branches/py3k/Demo/turtle/

The turtle module in Python 3.1 has a few enhancements (see docs)
and also two bugfixes.

Regards,
Gregor

  

--





  

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Bouncing mail

2009-07-22 Thread Wayne
On Wed, Jul 22, 2009 at 3:33 PM, Sander Sweers wrote:

> 2009/7/22 Dave Angel :
> > Anyone else seeing these?
>
> Unfortunately yes. Very annoying... :(


Yep, and not the only ones I've seen
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] xlwt & xlrd: can I refactor this code better?

2009-07-22 Thread Alan Gauld

"Albert-Jan Roskam"  wrote


Most functions have many arguments - isn't that called 'tight coupling'?


No. In fact too few parameters (arguments are what you pass in,
parameters are what you specify in the definition) often wind up
relying on global variables to share data - now THAT is tight coupling.


The first function is the main() function. Shouldn't a programmer strive
for information hiding in such a function?


Yes but only in terms of the algorithm and local variables. If you
genuinely need to pass in values then parameters are the correct
mechaniasm. You can sometimes reduce the param count by
building more complex data structures but that doesn't look to
be the case here. But 6 or so parameters is not excessive.
You can increase usability by providing default arguments,
but again you have already done that...


it should almost read like regular english, right?
Or is that too textbook-ish? ;-)


Its a good objective but don't become a slave to it.
You can do a lot with naming, but again you seem to have
tried there too.


def merge_xls(in_dir="d:/temp/", out_file="d:/temp/merged_output.xls"):
   """ Main function: merge xls sheets """


The doc string should say more about how to use the function.
What are each of the inputs and what is the output?
What errors are raised under what circumstances?


   xls_files = glob.glob(in_dir + "*.xls")
   xls_files.sort()
   merged_book = xlwt.Workbook()
   osheet_names = [os.path.basename(xls_file)[:-4] for xls_file in 
xls_files]

   for xls_no, xls_file in enumerate(xls_files):
   print "---> Processing file %s" % (xls_file)


I'm not a fan of print statements inside functions, it reduces their
reusability in Web/GUI applications.

def check_xls(book, merged_book, isheet_names, osheet_names, xls_no, 
xls_files):


def write_sheets(book, merged_book, isheet_names, osheet_names, xls_no, 
xls_files):


   else:
   raise Exception ("ERROR *** File %s has %s sheets (maximum is 99)" 
% (xls_file, book.nsheets))


Don't do this!
Create a new exception class specific to your functions.

This way the client has no alternative but to use

try:
except:

which will catch all exceptions. Then they must examine the exception data
to see what kind they have caught, that's a lot of work for the client just
to save you doing

class XLSFileError(Exception): pass

and

raise XLSFileError()

HTH,


--
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/ 



___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] how to fill zero value and join two column

2009-07-22 Thread Alan Gauld
 wrote 


I have two text file, having entries as
fileA
38 ALA H = 8.29 N = 120.62 CA = 54.33 HA = 4.04 C = 178.95
8 ALA H = 7.85  N = 123.95 CA = 54.67 HA =  C =
fileB
8 ALA  helix (helix_alpha, helix1)
21 ALA  helix (helix_alpha, helix2)
...
those atoms which doesnot have nay value in fileA. so the reult will be
something like:-

fileC
8 ALA H = 7.85  N = 123.95 CA = 54.67 HA =0.00  C =0.00|8 ALA  helix
(helix_alpha, helix1)


There is a similar problem discussed a few days ago on tis list, 
try looking over the archive for this week to get some ideas.



I tried to merge these two files using commands like:-

from collections import defaultdict

def merge(sources):

...   if __name__ == "__main__":


You should not use this inside a function, nor at the >>> prompt. 
This is used to determine wheher a file should be treated as a 
module or main program. As it stands the rest of your code will 
never be executed since the __name__ at the >>> prompt 
is never __main__


Looks like you need to go back to fundamentals for a spell.



...a = open("/home/amrita/alachems/chem100.txt")
...c = open("/home/amrita/secstr/secstr100.txt")
...def source(stream):
...return (line.strip() for line in stream)
...for m in merge([source(x) for x in [a,c]]):
...print "|".join(c.ljust(10) for c in m)


I haven't quite got my head around the logic here but it 
looks to me like an overly elaborate solution. You could 
simplify the last for loop to just do


for m in merge([source(a),source(c)])

But of course that is a recursive function call to merge() and I 
can't see any terminating condition so it should loop forever 
(or until it reaches the recursion limit)...


HTH,


--
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] mnemonics to better learn Python

2009-07-22 Thread David
Dear List,

in order to memorize which Python sequences are mutable or immutable, I
focused on the SHAPE of the brackets that are associated with each type
of sequence.

For instance, a *list* is characterised by square brackets, [].
My mnemonic device to memorize that lists are mutable is this: "the
brackets have sharp edges, they could be trimmed, taking their edges off".

The same thing happens with *dictionaries* (which, okay, are not
sequences). Anyway, their brackets, {}, have sharp edges, hence they are
mutable.

*Tuples*, in turn, have perfectly 'round' brackets, (), and these
brackets obviously can't be improved upon by taking anything off them.
Hence: tuples are immutable.

That leaves us with *strings*, which are also not mutable. Here we have
no brackets, and this particular mnemonic device breaks down.

What I am interested in is finding out whether you use similar
techniques, and if so, which ones? How, for examples, do you make sense
of all those special characters that make regular expressions powerful?
Do you rely on rote learning, or do you employ some other technique?

I reckon that if we could come up with some tips and techniques as to
how to uncloud the thick information fog that any beginning programmer
has to wade through, the very first steps in learning Python could be
made more easy.

What insights can you share?

Curious,

David
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Option parser tools

2009-07-22 Thread Todd Matsumoto
Hello Tutors,

I'm building a script that now needs a command line interface.

I'm aware of optparse, but I'm wondering if there are any other tools that may 
be better for building the interface.

Cheers,

T
-- 
GRATIS für alle GMX-Mitglieder: Die maxdome Movie-FLAT!
Jetzt freischalten unter http://portal.gmx.net/de/go/maxdome01
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] File I/O help

2009-07-22 Thread Chris Castillo
*I'm supposed to be reading in names a grades from a text file like so:
*
Chris
100
89
76
0
Dave
56
45
30
23
10
0
Sara
55
76
78
60
0

*the 0 indicates that's the end of the student's grades and not an actual 0
number grade for the student. This is what my code looks like so far:*

from myFunctions import *

grades = []
names = []
gradeTotal = 0
numStudents = 0

inputFile = open("input.txt", "r" )# Read in a file with student names a
grades

for line in open("input.txt", "r"):# iterate through txt file with names
and grades
if line.strip().isdigit():
grade = float(line)# convert score into float type
gradeTotal += grade# adds score to running total
if grade != 0:
grade = grades.append(grade)
else:
name = line.strip()
name = names.append(name)# Append name to names list


studentTotal = str(len(names))# Get student total
grades.sort() # Sort the grades in ascending order

---
*and then I need to output something that looks like this:*

Name of student  76,89,100 - and then their letter grade average(A, B,
C, etc..)
Name of student  76,89,100 - and then their letter grade average(A, B,
C, etc..)

*How do I do this with the code I have so far ( if possible )*
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor