我在 if else 语句中使用 AND 和 OR 时遇到一些问题。这是我的代码:
if subject == 'history' or subject == 'History' and unit == 'WWII' or unit == 'ww2':
有什么想法可以解决这个问题吗?
最佳答案
阅读operator-precedence - 一些运算符比其他运算符绑定(bind)更强 - 要获得所需的逻辑输出,您应该使用 (
)
来构建逻辑条件。
总结:
Operator Description lambda Lambda expression if – else Conditional expression or Boolean OR and Boolean AND not x Boolean NOT in, not in, is, is not, <, <=, >, >=, !=, == Comparisons, including membership tests and identity tests | Bitwise OR ^ Bitwise XOR & Bitwise AND <<, >> Shifts +, - Addition and subtraction *, @, /, //, % Multiplication, matrix multiplication, division, floor division, remainder [5] +x, -x, ~x Positive, negative, bitwise NOT ** Exponentiation [6] await x Await expression x[index], x[index:index], x(arguments...), x.attribute Subscription, slicing, call, attribute reference (expressions...), [expressions...], {key: value...}, {expressions...} Binding or tuple display, list display, dictionary display, set display
操作符越早,它的绑定(bind)就越高。请参阅链接的 doku 以了解订阅上下文
关于python - If Else 语句、AND OR 逻辑运算和文本文件(使用 Python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48043754/