Python 条件语句中的括号
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4740419/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
parentheses in Python Conditionals
提问by Ben Keating
I have a simple question regarding the use of parentheses in Python conditional statements.
我有一个关于在 Python 条件语句中使用括号的简单问题。
The following two snippets works just the same but I wonder if this is only true because of it's 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 their any cases where I should definitely use them?
任何人都可以帮助阐明这一点吗?他们是否有任何我绝对应该使用它们的情况?
采纳答案by g.d.d.c
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:
在 Boolean 之前进行比较的其他答案是 100% 正确的。作为替代方案(对于您所演示的情况),您还可以使用它作为组合条件的一种方式:
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.
这样可以节省对 socket.gethostname 的单独调用,并且随着项目的增长或您必须授权其他主机,可以更轻松地添加其他可能的有效值。
回答by kindall
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:
也就是说,我曾经看到的一个指南(可能在实用 C 编程中)是这样说的:
- Multiplication and division first
- Addition and subtraction next
- Parentheses around everything else
- 先乘除
- 接下来加减法
- 围绕其他所有内容的括号
(Yes, IIRC they left out exponentiation!)
(是的,IIRC 他们省略了求幂!)
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.
这个想法是优先规则足够神秘,以至于不应该期望任何人都记住它们,无论是原始程序员还是阅读代码的维护程序员,因此最好使其明确。从本质上讲,括号既可以将意图传达给编译器,也可以作为下一个必须处理它的 schmoe 的文档。
I believe in Python those two statements will generate the same bytecode so you're not even losing any efficiency.
我相信在 Python 中,这两个语句将生成相同的字节码,因此您甚至不会失去任何效率。
回答by James
The parenthesis 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 parenthesis to indicate which 'or' that 'and' paired with.
括号只是强制操作顺序。如果您的条件句中有一个附加部分,例如“and”,则建议使用括号来指示“and”与哪个“或”配对。
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):
...
回答by James Thompson
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.
在 Python 和许多其他编程语言中,并非每个带有多个运算符的表达式都需要括号。这是因为运算符具有定义的优先级。有关Python 中运算符优先级的信息,请参阅此处的表格(第 5.15 节)。
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)
回答by jarondl
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.
看看手册。您在列表中的位置越高,运算符将在稍后应用。"or" 高于 "==" ,因此,在这种特殊情况下,答案是相同的。但是,为了可读性,并且可以肯定的是,我建议使用括号。
回答by The Godfather
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).
我一直认为这是PEP8 的一部分,但显然不是。然而,在您在 PEP、代码示例和文档中遇到的所有示例中,您永远不会看到多余的括号(例如,在 PyCharm 中甚至有这样的检查)。
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).
一般建议仅在提高可读性或您确实想要更改表达式计算顺序(例如(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, inwill be much more readable, but that's rather off-topic now)
在您的代码示例中,括号是完全多余的,只需使用即可if socket.gethostname() == "bristle" or socket.gethostname() == "rete":(在生产代码中,当然,in会更具可读性,但这现在已经偏离主题了)

