manxing
manxing

Reputation: 3305

if command in python

if "aa" or "bb" or "cc" or "dd" or "ee" or "ff" in attrs["show"]:
    self.xx = xxxx

I have a code like this, to check if attrs["show"] contains either of these strings, then assign some value to self.xx

But is this "IF" command is correct? Because from my results, it seems like this if command is always true(which is impossible)

Upvotes: 3

Views: 660

Answers (3)

PenguinCoder
PenguinCoder

Reputation: 4357

Your IF statement is not testing for anything. It WILL always evaluate as true, because of the way it is written.

You are asking python:

Is aa true
Is bb true
...

Python says 'Yes, "aa" is true, because its there!'

Correct your if statement or find a better way to find the values in the list:

any(x in ['aa','bb','cc','dd','ee','ff'] for x in attrs["show"])

Upvotes: 3

kindall
kindall

Reputation: 184091

In Python, and or evaluates to its first True operand (since True or'd with anything is True, Python doesn't need to look further than the first operand).

So:

"aa" or "bb" or "cc" or "dd" or "ee" or "ff" in attrs["show"]

... evaluates to:

"aa"

Which is True, because it's a non-empty string. The rest of the line is not even considered because it does not need to be.

So your if statement always executes because it is always True.

What you want is something like:

"aa" in attrs["show"] or "bb" in attrs["show"] or "cc" in attrs["show"] ...

This gets very wordy, so you can use any along with a generator expression to write it more succinctly.

any(s in attrs["show"] for s in ["aa", "bb", "cc", "dd", "ee", "ff"])

Upvotes: 4

Andrew Clark
Andrew Clark

Reputation: 208405

Try the following:

if any(s in attrs["show"] for s in ("aa", "bb", "cc", "dd", "ee", "ff")):
    self.xx = xxxx

Your current if statement will always evaluate to True, because instead of checking if each string is in attrs["show"] you are checking if "aa" is True, or if "bb" is True, and on and on. Since "aa" will always evaluate as True in a Boolean context, you will always enter the if clause.

Instead, use the any() function as in my example, which accepts an iterable and returns True if any of its elements are True. Similar to a bunch of or's as in your code, this will short-circuit as soon as it finds an element that is True. In this example, the above code is equivalent to the following (but much more concise!):

if ("aa" in attrs["show"] or "bb" in attrs["show"] or "cc" in attrs["show"] or
    "dd" in attrs["show"] or "ee" in attrs["show"] or "ff" in attrs["show"]):
    self.xx = xxxx

Upvotes: 15

Related Questions