Question on if, while, for

Paul Rubin phr-n2002a at nightsong.com
Mon Feb 11 09:17:50 EST 2002


c at tech.usd253.org (Fred) writes:
> I have written a simple program that I want to simplify. I used if and
> elif. But I am sure this can be simplified with for or while. Or what
> if I wrote a function to do the testing?
> 
> Please DO NOT re-write this for me I want to figure it out for myself.
> I would just like to know what is the BEST way to do it:
> 
> 1) For loop (nested??)
> 2) While loop
> 3) Function
> 4) Leave it alone it's fine??

5) Try to take a clearer look at the problem you're solving, rather
than getting wrapped up in the programming details.  You're trying to
reduce a fraction to lowest terms.  Never mind programming--how would
you explain that process to a math student?  I don't think you'd do it
the same way your program does it.  Try to make your program more
closely follow the methods you'd learn in a math class for reducing
fractions.  Only after you understand the math should you try to
express it as Python code.

I'll give a hint: you'll want to know how to compute the least common
denominator of two integers a and b.  You might want to look in a book
to find out how to do that.

Also (general advice): if you find yourself writing the almost same
thing over and over in a program (for example testing all those
divisors), that's a sure sign that you want to use a loop or a
subroutine.  As to deciding whether to use a for loop or while--try it
both ways and see which one you like better.  Even experienced
programmers sometimes code something two different ways to see which
one looks better on the screen.

Finally, a good book from the old days: The Elements of Programming
Style, by Kernighan and Plauger, has a bunch of examples (not in
Python) of complicated code and how to simplify it.  It's sort of
out-of-date now and I wouldn't recommend buying it at retail (it's
overpriced like many technical books) but if your local library has
it, you might like to look at it.



More information about the Python-list mailing list