2

I'm trying to do this -

word = 'hello'

if 'a' or 'c' in word:
    continue
elif 'e' in word:
    continue
else:
    continue

It only works if I don't have the or. The string is a single word.

whoisearth
  • 4,080
  • 13
  • 62
  • 130

4 Answers4

6

This:

if 'a' or 'c' in word:
    continue

Is equivalent to:

if ('a') or ('c' in word):
    continue

And 'a' is always True in boolean context, therefore continue is always performed due to short-circuiting.

Solution:

if any(c in word for c in ('a', 'c')):
    continue
Łukasz Rogalski
  • 22,092
  • 8
  • 59
  • 93
1

Replace if 'a' or 'c' in word: with if 'a' in word or 'c' in word. Generally you'll have to provide that in word for each character you are testing. You could also use any, but since your if is simple, you can just use the format above.

codingEnthusiast
  • 3,800
  • 2
  • 25
  • 37
1

1) It should be if 'a' in word or 'c' in word:

2) continue will raise SyntaxError, because you didnt use it in loop. If you dont do anything, you can use pass other than continue

Haifeng Zhang
  • 30,077
  • 19
  • 81
  • 125
0

You can use the any built-in function like so:

any(i in ('a', 'c') for i in word)
Malik Brahimi
  • 16,341
  • 7
  • 39
  • 70