Using the "or" conditions in an if condition

I am sure there is a very simple answer to this question, but I can not find it after searching for a while.

prefixes = "JKLMNOPQ" suffix = "ack" for letter in prefixes: if letter == "Q" or letter == "O": print letter + "u" + suffix else: print letter + suffix 

The above code works fine, the condition in the if statement looks a bit long, so I tried:

 if letter == "Q" or "O": 

which is shorter but not working. I decided that this would not work, because β€œO” is a logical expression that will always be True and that it does not consider anything on the left side β€œor”.

I tried putting brackets around it like this:

 if letter == ("Q" or "O"): 

but this only matches Q, not O.

Is there any shortcut way to make the code work, or do I need to use a long way that works for me?

+4
source share
5 answers

You can use letter in 'OQ' or re.match('[OQ]', letter)

In more detail, I would probably define a string of prefixes that should receive "u".

 prefixes = 'JKLMNOPQ' prefixes_taking_u = 'OQ' suffix = 'ack' for p in prefixes: u_part = 'u' if p in prefixes_taking_u else '' print p + u_part + suffix 

In your code, letter == ("O" or "Q") first evaluates ("O" or "Q") ("O" is not false, therefore the result is "O"), and therefore it is the same as letter == "O" .

Your other attempt letter == "O" or "Q" first evaluates letter == "O" , and if it is true, it gives the True answer, otherwise it will give the answer "Q".

You can find documentation on how or works in the help system.

+4
source

To implement the condition, use one of the following solutions:

  • list: if letter in ['Q', 'O']
  • tuple: if letter in ('Q', 'O')
  • string: if letter in 'QO'

Update . For completeness: Regexp: re.match('[OQ]', letter) (copied from Paul Hankins is responsible (you should vote for it if you think regexp is the solution))

+8
source
 if letter in ['Q', 'O'] 

btw, it's best not to focus on how to write code.

+1
source

And one more option (faster if there are many prefixes, and not just two):

 prefixes = frozenset('QO') if letter in prefixes: #... 
0
source

The "in string" option is best in this special case when the input is a single character. More generally, for a small number of possible values ​​"in a tuple" is preferable to "in a list", since the last Pythons will build a tuple at compile time, while the list is created at runtime.

When there are many options, a set or freezonset can be built once and polled several times quickly.

Regular expression approaches are more complex and / or slower than the options described above.

(1) re.match('[QO]', letter) cannot compete with letter in 'QO'

(2) initially needs_u = re.compile('[QO]').match followed by needs_u(letter) is awful compared to the initial needs_u = set('QO') followed by letter in needs_u

0
source

Source: https://habr.com/ru/post/1389782/


All Articles