Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parentheses in Python Conditionals

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?

like image 949
Ben Keating Avatar asked Jan 19 '11 20:01

Ben Keating


People also ask

Do Python conditionals need parentheses?

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

Can you put parentheses in IF statement?

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.

What are the 3 types of Python conditional statements?

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.

How do parentheses work in Python?

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.


2 Answers

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.

like image 103
g.d.d.c Avatar answered Oct 02 '22 12:10

g.d.d.c


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):     ... 
like image 31
James Avatar answered Oct 02 '22 13:10

James