'和'和'或'如何在Python中使用非布尔值?

sam*_*wei 0 python syntax

22 and 333/12 or 1
Run Code Online (Sandbox Code Playgroud)

我遇到了上面的代码行.结果是27,但我不太明白在这种情况下的意义andor含义.有人可以向我解释,首选的例子.提前致谢!!

Ism*_*awi 8

这是"和 - 或技巧" - and并且or实际上不返回布尔值; 相反,他们返回一个输入参数.人们习惯将此用于控制流程.

从python 2.5开始,它不再是必需的了,因为引入了条件表达式.

22 and 333/12 or 1
Run Code Online (Sandbox Code Playgroud)

相当于

333/12 if 22 else 1
Run Code Online (Sandbox Code Playgroud)

  • "`if else`"更具可读性.我希望人们还没有诉诸和/或欺骗. (5认同)

Cha*_*ffy 6

A and B 如果A为假,则返回A,否则返回B:

>>> 0 and 1
0
>>> False and True
False
>>> True and 'yes'
'yes'
>>> True and ''
''
Run Code Online (Sandbox Code Playgroud)

同样,如果A为真,'A或B'返回A,否则返回B:

>>> 0 or 1
1
>>> False or True
True
>>> '' or 'yes'
'yes'
>>> False or ''
''
>>> 'yes' or ''
'yes'
Run Code Online (Sandbox Code Playgroud)