Python 条件语句中的括号
我有一个关于 Python 条件语句中括号的使用的简单问题。
下面的两个片段的工作原理是一样的,但我想知道这是否只是因为它的简单而正确:
>>> import os, socket
>>> if ((socket.gethostname() == "bristle") or (socket.gethostname() == "rete")):
... DEBUG = False
... else:
... DEBUG = True
...
>>> DEBUG
现在没有括号
>>> import os, socket
>>> if socket.gethostname() == "bristle" or socket.gethostname() == "rete":
... DEBUG = False
... else:
... DEBUG = True
...
>>> DEBUG
有人可以帮助阐明这一点吗?在某些情况下我绝对应该使用它们吗?
I have a simple question regarding the use of parentheses in Python's conditional statements.
The following two snippets work just the same but I wonder if this is only true because of its simplicity:
>>> import os, socket
>>> if ((socket.gethostname() == "bristle") or (socket.gethostname() == "rete")):
... DEBUG = False
... else:
... DEBUG = True
...
>>> DEBUG
and now without parentheses
>>> import os, socket
>>> if socket.gethostname() == "bristle" or socket.gethostname() == "rete":
... DEBUG = False
... else:
... DEBUG = True
...
>>> DEBUG
Could anyone help shed some light on this? Are there any cases where I should definitely use them?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
括号只是强制执行操作顺序。如果条件语句中有附加部分,例如
and
,建议使用括号来指示and
配对的或
和。为了区别于
The parentheses just force an order of operations. If you had an additional part in your conditional, such as an
and
, it would be advisable to use parentheses to indicate whichor
thatand
paired with.To differentiate from
在这种情况下,括号是多余的。比较的优先级高于布尔运算符,因此无论括号如何,始终首先执行比较。
也就是说,我曾经看到的一个指南(也许在《实用 C 编程》中)是这样说的:
(是的,IIRC 他们省略了求幂!
)想法是,优先规则非常晦涩难懂,以至于没有人应该记住它们,无论是原始程序员还是阅读代码的维护程序员,因此最好将其明确化。本质上,括号既可以向编译器传达意图,也可以作为下一个必须处理它的 schmoe 的文档。
我相信在 Python 中这两个语句将生成相同的字节码,因此您甚至不会损失任何效率。
The parentheses are redundant in this case. Comparison has a higher precedence than Boolean operators, so the comparisons will always be performed first regardless of the parentheses.
That said, a guideline I once saw (perhaps in Practical C Programming) said something like this:
(Yes, IIRC they left out exponentiation!)
The idea being that the precedence rules are arcane enough that nobody should be expected to remember them all, neither the original programmer nor the maintenance programmer reading the code, so it is better to make it explicit. Essentially the parentheses serve both to communicate the intent to the compiler and as documentation for the next schmoe who has to work on it.
I believe in Python those two statements will generate the same bytecode so you're not even losing any efficiency.
我一直认为这是 PEP8 的一部分,但显然不是。然而,在 PEP、代码示例和文档中遇到的所有示例中,您永远不会看到多余的括号(例如,PyCharm 中甚至有这样的检查)。
一般建议仅在提高可读性或您确实想要更改表达式计算顺序(例如
(a 或 b) 和 c
)时才使用括号。做:
不做:
在您的代码示例中,括号完全是多余的,只需使用
if socket.gethostname() == "bristle" 或 socket.gethostname () == "rete":
(当然,在生产代码中,in
会更具可读性,但现在已经脱离主题了)I was always thinking that this is part of PEP8, but apparently it's not. However in all examples you meet in PEPs, code samples and documentation you never see redundant parentheses (there is even such an inspection in PyCharm, for example).
General recommendation is to use parentheses only if it improves readability or you actually want to change the order of expression calculation (such as
(a or b) and c
).Do:
Don't:
In your code sample, parentheses are completely redundant, just use
if socket.gethostname() == "bristle" or socket.gethostname() == "rete":
(in production code, of course,in
will be much more readable, but that's rather off-topic now)在 Python 和许多其他编程语言中,并非每个具有多个运算符的表达式都需要括号。这是因为运算符具有已定义的优先级。有关 Python 中运算符优先级的信息,请参阅此处表(第 5.15 节)。
你可以用算术来类比。这些表达式是等价的:
如果您想先添加三个,那么您需要使用括号,如下所示:
In Python and many other programming languages, parentheses are not required for every expression with multiple operators. This is because operators have a defined precedence. See the table here (Section 5.15) for information on operator precedence in Python.
You can draw an analogy to arithmetic. These expressions are equivalent:
If you mean to add three first, then you need to use the parentheses like this:
查看手册。您在列表中的排名越高,运算符将稍后应用。 “or”高于“==”,因此,在这种特殊情况下,答案是相同的。然而,为了可读性并且为了确定,我建议使用括号。
Have a look at the manual. The higher you are up in the list, the operator will be applied later. "or" is above "==" , and therefore, in this particular case the answers are the same. However, for readability, and just to be sure, I would recommend parenthesis.
我刚刚遇到类似的问题。我的条件语句是
第一个结果为True,第二个结果为False,第三个结果为True。直观上,这个条件语句的结果是正确的。然而,这是错误的。但下面这句话的结果是正确的;
我仍然没有弄清楚为什么会发生这种情况。
I just met a similar question. My conditional statement is
The first result is True, the second is False, and the third is True. Intuitively, the result for this conditional statement is true. However, it's false. But the result for the following sentence is correct;
I still have not figured out why this happening.
比较发生在布尔之前的其他答案是 100% 正确的。作为替代方案(对于您所演示的情况),您还可以使用此方法来组合条件:
这可以节省您对 socket.gethostname 的单独调用,并且随着项目的增长,可以更轻松地添加其他可能的有效值或者您必须授权其他主机。
The other answers that Comparison takes place before Boolean are 100% correct. As an alternative (for situations like what you've demonstrated) you can also use this as a way to combine the conditions:
That saves you the separate calls to socket.gethostname and makes it easier to add additional possible valid values as your project grows or you have to authorize additional hosts.