-4

When "if" is combined with "or", which one Python prioritize first: for example:

if a == b or c

is it (a == b) or c or is it a == (b or c). I assume the correct logical form should be the former one but I accidentally used:

if gender == "m' or "M" 

and to my surprise, it did not generate any errors and did the purpose.

cs95
  • 379,657
  • 97
  • 704
  • 746
Mercury
  • 3
  • 2
  • 1
    Question shows no research effort. A simple SO or Google search would reveal the answer. Please read and follow the posting guidelines: what kinds of questions can I ask https://stackoverflow.com/help/on-topic, and How to ask: https://stackoverflow.com/help/how-to-ask. Remember to also to include Minimal, complete, verifiable examples: https://stackoverflow.com/help/mcve. Then, click `edit` to edit your question so that we may help. – SherylHohman Sep 13 '17 at 05:15

1 Answers1

0

From the documentation:

The following table summarizes the operator precedence in Python, from lowest precedence (least binding) to highest precedence (most binding).

lambda
if – else 
or    
and
not x 
in, not in, is, is not, <, <=, >, >=, !=, ==  
...

So, to answer your question,

a == b or c

Is equivalent to

(a == b) or (c)

The code if gender == "m" or "M" will work like this: Is gender == 'm"? If yes, the result is True. Otherwise, test the "truthiness" of "M". Is "M" "true"? If it is, the result is true. To understand how this works, you should know that all objects have a truthiness associated to it. All non-zero integers, non-empty strings and data structures are True. 0, 0.0, '', None, False, [], {} and set() are all False.

For more details, visit How do I test one variable against multiple values?

cs95
  • 379,657
  • 97
  • 704
  • 746
  • Thank you, It is what seems logic to me and I have always used. But could you please explain how did what I used in my code work: – Mercury Sep 13 '17 at 06:28
  • @COLDSPEED: Thank you again. I appreciate such a clear explanation. – Mercury Sep 13 '17 at 23:14