"Josiah Manson" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> Hello. I am very new to Python, and have been unable to figure out how
> to check if a variable exists or not. In the following code

Python does not have variables is the sense some other languages do.  It 
has (typeless) names bound to typed objects with values.  This is a 
different object-value model and a different mindset from some other 
languages.

> I have made
> a kludge that works, but I think that it would be clearer to check if
> closest exists and not have to initialize it in the first place. How is
> that check done?

What you did is normal Python code.  Checking whether 'closest' is bound to 
anything can be done but that *is* a kludge, which I will leave for you to 
discover elsewhere.

> The following code finds the closest place to a position and rejects
> places that are too far away.
>
>        dist = 1e9
>        closest = -1

closest = None # is the standard for 'not bound to anything'

>        for n,p in galaxy.places.iteritems():
>            dif = p.pos - pos
>            len = dif.len()
>            if len < dist and len < 10.0/self.zoom:
>                dist = len
>                closest = p

If you generate a sequence of (distance, place) pairs, beginning with 
(1e99, None), you can select the mimimum distance pair with the min() 
builtin function instead of rewriting it.

>        if closest != -1:

if closest: # bool(None) == False, bool(anyplace) == True

>            self.sel = [closest.name]
>
> I also have a few other questions to tack on if you don't mind. I am
> setting dist to 1e9, because that is a larger value than any of the
> places in the galaxy will be far away. Is there a better way to
> initialize dist so that it is impossible for this to fail? For example,
> would setting dist to infinity work, and how is that done?

Maybe, depending on the compiler.  For now, I would stick with a known 
larger-than-possible value.

> Extending my existance checking question, how does one check what type
> a variable has?

See the first two sentences above and look up type() and isinstance() in 
the 2nd chapter of the Library reference.  (And do read that entire chapter 
if you have not.)

Terry J. Reedy



-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to