Python by Swaroop C H - HTML preview

PLEASE NOTE: This is an HTML preview only and some elements such as links or page numbers may be incorrect.
Download the book in PDF, ePub, Kindle for a complete version.

Operator Precedence

If you had an expression such as 2 + 3 * 4, is the addition done first or the multiplication? Our high school maths tells us that the multiplication should be done first - this means that the multiplication operator has higher precedence than the addition operator.

The following table gives the operator precedence table for Python, from the lowest precedence (least binding) to the highest precedence (most binding). This means that in a given expression, Python will first evaluate the operators lower in the table before the operators listed higher in the table.

The following table (same as the one in the Python reference manual) is provided for the sake of completeness. However, I advise you to use parentheses for grouping of operators and operands in order to explicitly specify the precedence and to make the program as readable as possible. For example,2 + (3 * 4) is definitely more clearer than2 + 3 * 4. As with everything else, the parentheses shold be used sensibly and should not be redundant (as in2 + (3 + 4)).

Table 5.2. Operator Precedence

Operator
lambda
or
and
not x
in, not in
is, is not
<, <=, >, >=, !=, ==

Description
Lambda Expression Boolean OR
Boolean AND
Boolean NOT
Membership tests Identity tests
Comparisons

Operator
|
^
&
<<, >>
+,
*, /, %
+x, -x
~x
**
x.attribute
x[index]
x[index:index] f(arguments ...) (expressions, ...) [expressions, ...] {key:datum, ...} `expressions, ...`

Description
Bitwise OR
Bitwise XOR
Bitwise AND
Shifts
Addition and subtraction
Multiplication, Division and Remainder Positive, Negative
Bitwise NOT
Exponentiation
Attribute reference
Subscription
Slicing
Function call
Binding or tuple display
List display
Dictionary display
String conversion

The operators which we have not already come across will be explained in later chapters. Operators with the same same precedence are listed in the same row in the above table. For example,+ and- have the same precedence.