Newbie help looping/reducing code

Paul Rubin http
Mon Feb 19 18:53:52 EST 2007


Lance Hoffmeyer <lance at augustmail.com> writes:
> T2B = even_odd_round(float(str(T2B)))	
> VS  = even_odd_round(float(str(VS)))	
> SS  = even_odd_round(float(str(SS)))	
> sh.Cells(21,lastcol+1).Value = float(str(T2B))/100
> sh.Cells(22,lastcol+1).Value = float(str(VS))/100
> sh.Cells(23,lastcol+1).Value = float(str(SS))/100

First of all, I don't understand float(str(VS)) and so forth; if VS is
(say) an integer, you can say float(VS) directly.  Second, even_odd_round
is written in a way that it can accept either an int or a float.

So assuming you need to keep those variables around, I'd write the
first three lines of the above as:

   T2B = even_odd_round(T2B)
   VS = even_odd_round(VS)
   SS = even_odd_round(SS)

or you could get fancier and say

   T2B, VS, SS = map(even_odd_round, (T2B, VS, SS))

Then you could write the next three lines as a loop:

   for i,v in ((21, T2B), (22, VS), (23,SS)):
     sh.Cells(i, lastcol+1) = float(v) / 100.0



More information about the Python-list mailing list