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

Steve Holden sholden at holdenweb.com
Wed Aug 8 13:54:44 EDT 2001


"Lee" <lee.r2d2 at ntlworld.com> wrote in message
news:3B71760B.B7FCBEC7 at ntlworld.com...
> 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 |
>
> ---
> fname[1] gives 'e'
>
> Thanks very much in advance!
>
The "|" operator implements a bitwise "or" on numeric operands. If what you
mean is

if (fname[1] == 'a' or fname[1] == 'e' ...):

then the most Pythonic way to spell this is probably

if fname[1] in "aeiou":
    vowel = 'true'

though unless you have already fixed the case of everything it might be
better to say

if fname[1].lower() in "aeiou":
    vowel = 'true'

As a further point, you COULD actually say

vowel = (fname[1].lower() in "aeiou")

The "vowel" name will then be bound to a truth value (in practice either 0
for false or 1 for true), and you can later write

if vowel:
    # handle a vowel

which will be quicker to write and run than

if vowel == 'true':
    # handle a vowel

regards
 Steve
--
http://www.holdenweb.com/








More information about the Python-list mailing list