Operator Precedence
You know that multiplication *
takes precedence over addition +
. That is,
the expression 5 + 4 * 3
is evaluated
as if it were parenthesized like this 5 + (4 * 3)
.
Mathematics has conventions for precedences of operators in order to reduce the number of
parentheses required in writing complex expressions. Some of these conventions are
standard throughout the world, such as *
over +
. Others are not.
Table of Contents
Precedence Table
Below is a table of precedences for Python operators. Refer to this table, or the one on p. 12 of the text Think Python 2nd edition, if you forget the precedences.
Order | Operators | Examples |
---|---|---|
Highest | Parentheses | ( ) |
Exponentiation | ** |
|
Unary arithmetic ops | +x
–x |
|
Binary arithmetic ops | *
/
//
% |
|
Binary arithmetic ops | +
– |
|
Arithmetic relations | <
>
<=
>= |
|
Equality relations | ==
!= |
|
Logical not | not |
|
Logical and | and |
|
Lowest | Logical or | or |
For example, the expression
can be easily rewritten as
because relational operators have precedence over logical and
.
Parentheses Usage
Avoid redundant parentheses
Your goal in writing expressions should be to make them a clear and simple-looking as possible. To many parentheses will ensure Python does what you say, but they can be hard to read. They best way to help the reader is to put more space around operators with less precedence. For example, the two assignment statements shown below have the same meaning, but the second is easier to read:
One place where we see a lot redundant parentheses is in return statements. They are not needed here. The following two statements are equivalent, but the second is easier to read:
Use parentheses for long lines of code
One area where parentheses are necessary is for extremely long lines of code. It is standard convention to limit each line of code to less than 80 characters (for purposes of readability). However, Python is a “whitespace-significant” language, which means that spaces and indentation have specific meanings and Python and cannot be used frivolously to make the code look pretty.
Fortunately, if an expression is in parentheses, you can break it up across several lines. For example, the following is acceptable Python code: below have the same meaning, but the second is easier to read:
When using parentheses to break up code across multiple lines, it is standard practice to indent the lines so that they start just after the position of the initial parenthesis. This is shown in the example above.