if-else with '|' operator - beginner's question/problem

Thomas Wouters thomas at xs4all.net
Wed Aug 8 19:59:08 CEST 2001


On Wed, Aug 08, 2001 at 06:25:31PM +0100, Lee wrote:

> Hi there, I wonder if someone could possibly tell me what is wrong with
> the following statement. I'm extremely embarrased to ask but here
> goes...

> >>>  if (fname[1] == 'a'|'e'|'i'|'o'|'u'):
>     vowel='true'

> Traceback (innermost last):
>   File "<pyshell#46>", line 1, in ?
>     if (fname[1] == 'a'|'e'|'i'|'o'|'u'):
> TypeError: bad operand type(s) for |

'|' is the 'bitwise OR' operator. It takes the numerical values you feed it
(or anything that defines __or__) and OR's them together, bit by bit. 

What you were looking for is the 'logical OR' operator, '||', but applied
differently. You have to do it like this:

    if (fname[1] == 'a' || fname[1] == 'e' || # ... etc...

Or, even better, in a more Pythonic style:

    if (fname[1] in ('a', 'e', 'i', 'o', 'u')):

or, equivalently but slightly more obfuscated:

    if (fname[1] in 'aeiou'):

(The latter works because a string is a sequence too.)

-- 
Thomas Wouters <thomas at xs4all.net>

Hi! I'm a .signature virus! copy me into your .signature file to help me spread!




More information about the Python-list mailing list