[Tutor] First program

Steven D'Aprano steve at pearwood.info
Sat Mar 13 04:15:37 CET 2010

On Sat, 13 Mar 2010 01:04:42 pm Ray Parrish wrote:
> >     print "A %s with dimensions %sx%s has an area of %s." %
> > (choice, height, width, width*height)
> Hello,
> 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.

Of course you are welcome to use whatever coding standards you like, but 
I think you will find that among experienced coders, you are in a 
vanishingly small minority. As a beginner, I found string interpolation 
confusing at first, but it soon became second-nature. And of course, 
there are legions of C coders who are used to it.

I find an expression like:

"The area of a " + Choice + "is " str(Width) + " x " + str(Height) 
+ "equals " + str(Width * Height) + "square feet"

difficult to follow: too many quotes, too many sub-expressions being 
added, too many repeated calls to str(), it isn't clear what is the 
template and what is being inserted into the template. It is too easy 
to miss a quote and get a SyntaxError, or to forget to add spaces where 
needed. To me, this is MUCH easier:

template = "The area of a %s is %s x %s equals %s square feet"
print template % (Width, Height Width*Height)

One pair of quotes instead of five, no problems with remembering to add 
spaces around pieces, and no need to explicitly call str().

Steven D'Aprano

More information about the Tutor mailing list