[Tutor] Re: %d
Alan Gauld
agauld@crosswinds.net
Wed, 23 May 2001 10:22:30 +0100
>In Alan Gauld's tutorial page 2 you suddenly move
> from gentle hand holding to this:
>
>>>>print "The sum of %d and %d is: %d" % (v,w,x)
Not sure where you get page 2 from but in the 4th chapter we introduce that
notation as below:
-------------
>>>print 'The total is: ', 23+45
You've seen that we can print strings and numbers. Now we combine the two in
one print statement,
separating them with a comma. We can extend this feature by combining it with
a useful Python trick for
outputting data called a format string:
>>> print "The sum of %d and %d is: %d" % (7,18,7+18)
In this command the format string contains '%' markers within it. The letter
'd' after the % tells Python
that a 'decimal number' should be placed there. The values to fill in the markers
are obtained from the
values inside the bracketed expression following the % sign on its own.
There are other letters that can be placed after the % markers. Some of these
include:
%s - for string
%x - for hexadecimal number
%0.2f - for a real number with a maximum of 2 decimal places
%04d - pad the number out to 4 digits with 0's
The Python documentation will give lots more...
-----------------------
There then follows a chapter on data which introduces the concept of variables.
Then in the 6th chapter I use the line you quote above.... I recommend you read
the topics in order
using the master sitre at:
http://www.crosswinds.net/~agauld
or the zip/tgz files that you can download from there.
I do try to explain all concepts before using them!
Alan G.
>I thought % was for the modulus function.
It is, but is also used for formatting.
> So what is that % doing in front of d which
> I assume to be a built in variable?
See the excerpt from simple seqiuences quoted above
>I've carried on through Alan's explanation of "for"
> and "while". This is easy to use
You need to go back not forward, the explanation is
in chapter 3...
>Sorry if this is a little less challenging than interfaces to
>Postgres...
Now I'm confusded, I've never written an interface
to PostGres in my life! :-)
HTH,
Alan G