parentheses in Python Conditionals

北慕城南 提交于 2019-11-30 04:33:11

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.

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.

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):
    ...

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.

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)

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!