Re: Simple Python problem...

Ken Manheimer (klm@NIST.GOV)
Thu, 16 Feb 1995 10:51:33 -0500 (EST)

As a few people have mentioned, you need to use a 'global' statement or
else the reference to seqno will be local. The reason, however, is
slightly different than indicated in answers that i've seen.

> >seqno = 0
> >
> >def SomeFunc():
> > print 'Using serial #' + seqno
> > seqno = seqno+1

In python, a name that "is bound anywhere in the code block is local
in the entire code block; all other names are considered global."
(Courtesy of the python reference manual.) You can look at the global
statement as declaring that you may change the value of the designated
global vars, as opposed to just referring to them.

The upshot is that the seqno assignment statement localizes all
references within the block. In the absence of a binding, the
references would be global, but with it an explicit 'global' directive
becomes necessary.

While i'm being compulsive,-) i have one more, tiny nit to pick. Tom
Jones wrote:

> print 'Using serial ' + `seqno`:
>
> Notice also that you can't print an integer type
> you must convert it to a string......
> (Thus the back-quotes)

Actually, you can print an integer type. However, you can't add
string and integer types directly together. The backquotes above are
useful to get a string representation from the integer type, which you
then can add to the other string.

An alternative, for example:

print 'Using serial', seqno

would work, but there's a forced space between the two. So you couldn't
get 'Using serial #10' without using something like the string addition of
the backquoted representation, or '%' formatting, or some such.

I realize that these are small distinctions, but they're useful things
to know...

Ken
ken.manheimer@nist.gov, 301 975-3539