If the command in python

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

      

I have some code like this to check if attrs ["show"] contains any of these lines, then assigns some value to self.xx

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

+3


source to share


3 answers


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 as True

, because instead of checking if each line is in attrs["show"]

, you are checking to see if the value "aa"

is True, or if it "bb"

is True and on and off. Since "aa"

will always evaluate to True in a boolean context, you will always be entering a clause if

.



Instead, use a function any()

like in my example, which takes an iterable and returns True if any of its elements are True. Like a set or

like in your code, it will short-circuit as soon as it finds an element 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

      

+15


source


In Python, or

its first operand is evaluated True

(since True

or'd with anything True

, Python should not look beyond the first operand).

So:

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

      

... is evaluated as:

"aa"

      

What is True

it because it is a non-empty string. The rest of the line is not even considered because it is not needed.



So your statement is if

always executed 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 verbose, so you can use it any

along with a generator expression to write it more concisely.

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

      

+4


source


Your operator IF

is not testing anything. He WILL always evaluates to true, because as it is written.

You are asking python:

Is aa true
Is bb true
...

      

Python says, "Yes," ah ", it's true because there!"

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

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

      

+3


source







All Articles