Python 条件语句中的括号

发布于 2024-10-12 17:18:06 字数 576 浏览 10 评论 0原文

我有一个关于 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

烏雲後面有陽光 2024-10-19 17:18:07

括号只是强制执行操作顺序。如果条件语句中有附加部分,例如 and,建议使用括号来指示 and 配对的 和。

if (socket.gethostname() == "bristle" or socket.gethostname() == "rete") and var == condition:
    ...

为了区别于

if socket.gethostname() == "bristle" or (socket.gethostname() == "rete" and var == condition):
    ...

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 which or that and paired with.

if (socket.gethostname() == "bristle" or socket.gethostname() == "rete") and var == condition:
    ...

To differentiate from

if socket.gethostname() == "bristle" or (socket.gethostname() == "rete" and var == condition):
    ...
一个人的夜不怕黑 2024-10-19 17:18:07

在这种情况下,括号是多余的。比较的优先级高于布尔运算符,因此无论括号如何,始终首先执行比较。

也就是说,我曾经看到的一个指南(也许在《实用 C 编程》中)是这样说的:

  1. 首先是乘法和除法,然后是
  2. 加法和减法,
  3. 其他所有内容都用括号括起来

(是的,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:

  1. Multiplication and division first
  2. Addition and subtraction next
  3. Parentheses around everything else

(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.

桃扇骨 2024-10-19 17:18:07

我一直认为这是 PEP8 的一部分,但显然不是。然而,在 PEP、代码示例和文档中遇到的所有示例中,您永远不会看到多余的括号(例如,PyCharm 中甚至有这样的检查)。

一般建议仅在提高可读性或您确实想要更改表达式计算顺序(例如 (a 或 b) 和 c)时才使用括号。

  if (first_expr or second_expr) and third_expr:    

  if first_expr or second_expr:

不做

  if ((first_expr or second_expr) and third_expr):    

  if (first_expr):

  if (first_expr or (second_expr and third_expr)):

在您的代码示例中,括号完全是多余的,只需使用 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:

  if (first_expr or second_expr) and third_expr:    

  if first_expr or second_expr:

Don't:

  if ((first_expr or second_expr) and third_expr):    

  if (first_expr):

  if (first_expr or (second_expr and third_expr)):

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)

请恋爱 2024-10-19 17:18:07

在 Python 和许多其他编程语言中,并非每个具有多个运算符的表达式都需要括号。这是因为运算符具有已定义的优先级。有关 Python 中运算符优先级的信息,请参阅此处表(第 5.15 节)。

你可以用算术来类比。这些表达式是等价的:

5 * 5 + 3

(5 * 5) + 3

如果您想先添加三个,那么您需要使用括号,如下所示:

5 * (5 + 3)

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:

5 * 5 + 3

(5 * 5) + 3

If you mean to add three first, then you need to use the parentheses like this:

5 * (5 + 3)
撩起发的微风 2024-10-19 17:18:07

查看手册。您在列表中的排名越高,运算符将稍后应用。 “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.

一曲爱恨情仇 2024-10-19 17:18:07

我刚刚遇到类似的问题。我的条件语句是

if count1==0 & count2==0 & count3==0:

第一个结果为True,第二个结果为False,第三个结果为True。直观上,这个条件语句的结果是正确的。然而,这是错误的。但下面这句话的结果是正确的;

if (count1==0) & (count2==0) & (count3==0): 

我仍然没有弄清楚为什么会发生这种情况。

I just met a similar question. My conditional statement is

if count1==0 & count2==0 & count3==0:

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;

if (count1==0) & (count2==0) & (count3==0): 

I still have not figured out why this happening.

ヤ经典坏疍 2024-10-19 17:18:06

比较发生在布尔之前的其他答案是 100% 正确的。作为替代方案(对于您所演示的情况),您还可以使用此方法来组合条件:

if socket.gethostname() in ('bristle', 'rete'):
  # Something here that operates under the conditions.

这可以节省您对 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:

if socket.gethostname() in ('bristle', 'rete'):
  # Something here that operates under 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文