[Tutor] First program

Luke Paireepinart rabidpoobear at gmail.com
Sat Mar 13 03:31:56 CET 2010


Ray, please reply on-list in the future in case someone else has input.

On Fri, Mar 12, 2010 at 8:01 PM, Ray Parrish <crp at cmc.net> wrote:

> Luke Paireepinart wrote:
>
>    print "A %s with dimensions %sx%s has an area of %s." % (choice, height,
>> width, width*height)
>>
>>
> Isn't it a little more understandable to use a construct like the
> following?
>
> >>> print "The area of a " + Choice + "is " str(Width) + " x " +
> str(Height) + " equals " + str(Width * Height) + " square feet"
>
> The area of a rectangle is 12 x 10 equals 120 square feet.
>
> I find that putting the variables on the end like that, when you're not
> actually applying any special formatting to them makes it less readable when
> I'm debugging my stuff, or when someone else is reading my code, and trying
> to understand it.
>
>
> Your version creates at least 10 intermediate strings before outputting.
Remember strings are immutable in Python.
So you're constructing strings
The area of a
The area of a rectangle
The area of a rectangle is
12
The area of a rectangle is 12
The area of a rectangle is 12 x
10
The area of a rectangle is 12 x 10
The area of a rectangle is 12 x 10 equals
120
The area of a rectangle is 12 x 10 equals 120
The area of a rectangle is 12 x 10 equals 120 square feet

With string formatting you avoid all of these intermediate strings, so it's
arguably more efficient.
Other than just viewing from a performance standpoint though, I find it much
easier to read my version, because any computation required takes place at
the end of the line.
For example, your inline str(width*height) requires you to read the whole
line to see it.

It's really a personal thing, it's easier for me to read the formatting
version than the string concatenation version, in most cases.
Now if you had used the comma convention I would have seen your point.  This
is, I think, the easiest to read of all 3
area = width * height
print "The area of a", choice, "is", width, "x", height, ", which equals",
area, "square feet."

Also, why are you capitalizing variable names?  That's a pretty unusual
convention.

-Luke
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100312/09072676/attachment.html>


More information about the Tutor mailing list