febasnatt
febasnatt

Reputation: 47

Trouble with or, and, and not in if statments in Python

For some reason it always passes everything through.

if (keyphrase or keyphrase2 in comment.body) and ("Proof" or "proof" or "roof" or "Roof" or "woof" or "Woof" not in comment.body):
#do stuff

I'm new to Python sorry.

Upvotes: 2

Views: 58

Answers (2)

jedwards
jedwards

Reputation: 30200

You may expect:

if (x or y in z):

To be the same as:

if (x in z) or (y in z):

But in reality it's:

if (x) or (y in z):

So any True-like value of x will allow you to enter the if block body.

There are a few options to get what it seems like you're looking for, one is the any function and a generator expression):

if any(thing in z for thing in [x,y])

Upvotes: 1

blhsing
blhsing

Reputation: 106445

You should use any and all with generator expressions to test multiple values for membership:

if any(k in comment.body for k in (keyphrase, keyphrase2)) and all(k not in comment.body for k in ("Proof", "proof", "roof", "Roof", "woof", "Woof")):

Upvotes: 2

Related Questions