On Thu, 13 Sep 2007, Adam Bark wrote:

> The problem is what if it's an empty list or tuple? It would pass but have
> not value
> whereas if x would work fine.

Exactly.  The poster stated that x is supposed to be either None or a 
tuple of two floats.

Just to put a bit of meat on the example, let's create a function whose 
job is to return x[1]/x[0], but only if x[0] > 0.  Otherwise, it just 
falls off, i.e., returning None.

Here are two versions, one using "if x" is None; the other using just 
"if x"

>>> def test01(x):
...  if x is not None:
...   if x[0]>0:
...    return x[1]/x[0]
...
>>> def test02(x):
...  if x:
...   if x[0]>0:
...    return x[1]/x[0]


When x is None, both work:

>>> x = None
>>> print test01(x)
None
>>> print test02(x)
None

When x is, in fact, a tuple of two floats, both work:

>>> x = (2.0, 5.0)
>>> print test01(x)
2.5
>>> print test02(x)
2.5

Now... if x is an empty tuple:

>>> x = tuple()
>>> print test01(x)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in test01
IndexError: tuple index out of range
>>> print test02(x)
None
>>>

The first one, which checks "if x is None" fails.  This is a good thing.  

The second one, which just checks "if x" and is satisfied with any false
value, including an empty tuple, does not raise the error condition, even
though the data is bad.  This is a bad thing.



_______________________________________________
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

Reply via email to