[Tutor] First program

Ray Parrish crp at cmc.net
Sat Mar 13 18:45:33 CET 2010


Steven D'Aprano wrote:
> 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().
>   
OK, that does seem a bit easier now to me. I'm going to have to read up 
on the %s, and any other formatting % codes there are however, since I'm 
dead green in Python yet. 8-)

So, would I read about those in the string module portion of the 
documentation?

Thanks, Ray Parrish


-- 
Linux dpkg Software Report script set..
http://www.rayslinks.com/LinuxdpkgSoftwareReport.html
Ray's Links, a variety of links to usefull things, and articles by Ray.
http://www.rayslinks.com
Writings of "The" Schizophrenic, what it's like to be a schizo, and other
things, including my poetry.
http://www.writingsoftheschizophrenic.com




More information about the Tutor mailing list