python - If Else 语句、AND OR 逻辑运算和文本文件(使用 Python)

标签 python if-statement text-files logical-operators

我在 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/

相关文章:

看不到错误

PHP While 语句显示与查询结果相同的结果

c - C 中使用 strtol 逐行读取文本文件

ubuntu - Python:简单的 for 循环语法错误

python - Blaze 数据字段映射抛出 TypeError

python - 为什么变量不循环上传?

python - 当文件达到一定行数时,如何删除文本文件中的第一行?

python - 动态规划 - 原始计算器 Python

r - 提取向量的位置和值

python - 从文本文件创建字典 Python Numpy