为什么此条件表达式不生成 SyntaxError?

Why doesn't this conditional expression generate a SyntaxError?

当"if"与"or"组合时,哪个Python优先: 例如:

if a == b or c

(a == b) or c还是a == (b or c)。 我认为正确的逻辑形式应该是前者,但我不小心使用了:

if gender == "m' or "M" 

令我惊讶的是,它没有产生任何错误并且达到了目的。

来自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, <, <=, >, >=, !=, ==  
...

所以,为了回答你的问题,

a == b or c

等同于

(a == b) or (c)

代码 if gender == "m" or "M" 将像这样工作: gender == 'm" 是吗?如果是,则结果为True。否则,测试"M"的"truthiness"。是"M""true"?如果是,则结果为真。要理解这是如何工作的,您应该知道所有对象都具有与之关联的真实性。所有非零整数、非空字符串和数据结构都是True00.0''NoneFalse[]{}set()都是False.

更多详情,请访问How do I test one variable against multiple values?