-1

I have this code:

Split = Message.Body.split()
split = Split

if 'a' or 'b' or 'b' in split:
    time.sleep(2)
    print '1'
elif 'c' or 'd' in split:
    time.sleep(2)
    print '2'
elif 'e' or 'f' in split:
    time.sleep(2)
    print '3'
else:
    time.sleep(2)
    print '4'

I have used split to separate the words from my message and I want if a certain message is received to print a certain word, but now it only prints 1 regardless of the input.

Mike Müller
  • 82,630
  • 20
  • 166
  • 161
worer
  • 103
  • 2
  • 11
  • 1
    What do you think 'a' converted to a Boolean would be? The 'or' isn't doing what you think – TZHX Dec 28 '15 at 11:17
  • No, the 'a' wont be converted to boolean because I think `if 'a' or 'b' or 'b' in split:` is the same as this `if 'a' in split or 'b' in split or 'b' in split` – worer Dec 28 '15 at 11:19
  • Why do you think that? – TZHX Dec 28 '15 at 11:19
  • Originally I wanted to write something like this but it is not possible `if(split == "a" || spit == "b" || split == "c")` I believe that because I read it on a website but now that I think about it, it does not make sense. – worer Dec 28 '15 at 11:20
  • @worer: try `print(split)` and you'll understand why `split == "a"` or similar won't work. Also, `||` is not Python! ;) – Andrea Corbellini Dec 28 '15 at 11:22
  • Yeah I know it is not :), thank you for your time – worer Dec 28 '15 at 11:25

2 Answers2

5

This is the problem:

>>> 'a' or 'b' or 'b'
'a'

This is the solution:

if 'a' in split or 'b' in split:

Or, if you have many letters to check:

if any(x in split for x in 'ab'):

works better for this case:

if any(x in split for x in 'abcdefg'):
Mike Müller
  • 82,630
  • 20
  • 166
  • 161
0

An arguably more pythonic solution, especially for more cases:

cases = [('ab', 1), ('cd', 2), ('ef', 3)]

for key, value in cases:
    if any(x in split for x in key):
        time.sleep(2)
        print(value)
        break
else:
    time.sleep(2)
    print(4)
Mike Müller
  • 82,630
  • 20
  • 166
  • 161