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?
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 ).
You should generally use the parenthesis when you have to, and that would be when issues with operator presedence occur. @JFit OP is talking about ( ) inside the conditional expression, not { } wrapping the body of the if statement.
In Python, we can write “if” statements, “if-else” statements and “elif” statements in one line without worrying about the indentation. In Python, it is permissible to write the above block in one line, which is similar to the above block.
When we call a function with parentheses, the function gets execute and returns the result to the callable. In another case, when we call a function without parentheses, a function reference is sent to the callable rather than executing the function itself.
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 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): ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With