Sunday, November 3, 2019

conditional statements - Multiple 'or' condition in Python




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.


Answer



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':


No comments:

Post a Comment

hard drive - Leaving bad sectors in unformatted partition?

Laptop was acting really weird, and copy and seek times were really slow, so I decided to scan the hard drive surface. I have a couple hundr...