Hmm... An idea: if a,b==c,d:

Chad Netzer cnetzer at mail.arc.nasa.gov
Mon Nov 18 19:55:04 EST 2002


This is top posting (putting you reply before text you are replying to).

On Monday 18 November 2002 16:09, Richard Dillingham wrote:
> What's top-posting?

   See above.

> Also, I knew that a,b normally evaluates to a tuple, but it already doesn't
> in an if-statement. I get a syntax error instead.

There have been enough responses to this, so I'll try to be terse:

if 1:    -->  not a syntax error
if (1,):  --> not a syntax error
if 1,:  --> a syntax error

Why?

Because (for example) this is an expression:

(1,) != (0,)

and this is a syntax error:

1, != 0,

If you fail to add the parenthesis, then why not write this:

if 1,2 == 3,4:

as this:

if 1,2, == 3,4,:

which is a syntax error.  The paretheses make your intentions clearer (and 
hence, are so often seen surrounding tuples.

However, this is still not what you want, because:

>>> (1, 2==3, 4)
(1, 0, 4)
>>> 1,2 == 3,4
(1, 0, 4)

Now you are constructing a tuple, and the '==' is used to detemine whether 
the middle value is true or false.  The whole expression then gets executed 
if the tuple as a whole compares true or false.

In short, don't do this!

Instead, unpack your tuple and create a single expression:

if ((a == c) and (b == d)):

In general, trying to get fancy in an if statement is asking for trouble.  
Either do the tricky expression above it, and save the truth value, or be 
very explicit in the order you wish things to evaluate (or both).

-- 
Bay Area Python Interest Group - http://www.baypiggies.net/

Chad Netzer
cnetzer at mail.arc.nasa.gov




More information about the Python-list mailing list