Complex compound expressions

Erik Max Francis max at alcyone.com
Sat Aug 17 00:39:39 CEST 2002


Derek Basch wrote:

> Just a quick question. I am still a little shaky on
> using parentheses to form complex compound
> expressions. For example:
> 
> if character in string.letters or string.digits:
>             print 'im a character'
> 
> this prints 'im a character' for every character
> including digits and whitespaces.

That's because or is merely a logical operator.  Your expression

	c in a or b

is really equivalent to

	(c in a) or b

which will always evaluate to true, regardless of c and a, if b is a
non-empty string.

> I can get the
> desired result by using this expression:
> 
> if character in string.letters or character in
> string.digits:
>            print 'im a character'

This is the proper approach.

> However, I know that there must be a way to use a
> parentheses on the top statement and get the same
> result. Can anyone help me out here?

Why do you think there is a way to use the shorthand you want?  It is
actually not all that common in programming languages (though some do
have it).  There _is_ a particular shorthand you can use here, since
string.letters and string.digits are both strings:  You can concatenate
them with the + operator and then test against that:

	if character in (string.letters + string.digits):
	    ...

Remember, though:  Brevity is not in and of itself a good thing. 
Clarity should almost always win out over brevity.

-- 
 Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/
 __ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE
/  \ There is nothing so subject to the inconstancy of fortune as war.
\__/ Miguel de Cervantes
    Church / http://www.alcyone.com/pyos/church/
 A lambda calculus explorer in Python.



More information about the Python-list mailing list