Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple 'or' condition in Python [duplicate]

Tags:

I have a little code issue and it works with IDLE and not with Eclipse, can I write this :

if  fields[9] != ('A' or 'D' or 'E' or 'N' or 'R'): 

instead of this :

if  fields[9] != 'A' and fields[9] != 'D' and fields[9] != 'E' and fields[9] != 'N' and fields[9] != 'R': 

Thank you.

like image 289
katze Avatar asked Mar 10 '14 15:03

katze


People also ask

Can you use || in Python?

If you use && operator in Python, you will get the SyntaxError. Likewise, || and ! are not valid Python operators. So instead, use or and not operator.

How do you write multiple conditions in Python?

Test multiple conditions with a single Python if statement To test multiple conditions in an if or elif clause we use so-called logical operators. These operators combine several true/false values into a final True or False outcome (Sweigart, 2015).

How do you check multiple conditions in one if statement?

Here we'll study how can we check multiple conditions in a single if statement. This can be done by using 'and' or 'or' or BOTH in a single statement. and comparison = for this to work normally both conditions provided with should be true. If the first condition falls false, the compiler doesn't check the second one.


2 Answers

Use not in and a sequence:

if fields[9] not in ('A', 'D', 'E', 'N', 'R'): 

which tests against a tuple, which Python will conveniently and efficiently store as one constant. You could also use a set literal:

if fields[9] not in {'A', 'D', 'E', 'N', 'R'}: 

but only more recent versions of Python (Python 3.2 and newer) will recognise this as an immutable constant. This is the fastest option for newer code.

Because this is one character, you could even use a string:

if fields[9] not in 'ADENR': 
like image 195
Martijn Pieters Avatar answered Oct 06 '22 10:10

Martijn Pieters


You want the in operator:

if fields[9] not in 'ADENR':     ... 

Or, you could use any:

if not any(fields[9] == c for c in 'ADENR'):     ... 

Or, alternatively, all, which may have a bit more of the same form as the original:

if all(fields[9] != c for c in 'ADENR'):     ... 

As an aside:

if x != ('A' or 'B' or 'C'): 

is really the same thing as saying:

if x != 'A': 

because 'A' or 'B' or 'C' evaluates to 'A' (Try it!). The reason is because with or, python will return the first "non-falsey" value (or the last one if they're all falsey). Since non-empty strings are non-falsey, the first one gets returned.

like image 22
mgilson Avatar answered Oct 06 '22 09:10

mgilson