Source

Chapter 5. Operators and Expressions

Most statements (logical lines) that you write will contain expressions. A simple example of an expression is 2 + 3. An expression can be broken down into operators and operands.

Operators are functionality that do something and can be represented by symbols such as + or by special keywords. Operators require some data to operate on and such data are called operands. In this case, 2 and 3 are the operands.

Operators

We will briefly take a look at the operators and their usage:

System Message: ERROR/3 (/home/gerard/environments/sphinx-0.5-with-patch/thehazeltree/source/byteofpython/5.rst, line 18)

Content block expected for the “tip” directive; none found.

.. tip::

You can evaluate the expressions given in the examples using the interpreter interactively. For example, to test the expression 2 + 3, use the interactive Python interpreter prompt:

>>> 2 + 3
5
>>> 3 * 5
15
>>>

Table 5.1. Operators and their usage

Operator Name Explanation Examples + Plus Adds the two objects 3 + 5 gives 8. ‘a’ + ‘b’ gives ‘ab’. - Minus Either gives a negative number or gives the subtraction of one number from the other -5.2 gives a negative number. 50 - 24 gives 26. * Multiply Gives the multiplication of the two numbers or returns the string repeated that many times. 2 * 3 gives 6. ‘la’ * 3 gives ‘lalala’. ** Power Returns x to the power of y 3 ** 4 gives 81 (i.e. 3 * 3 * 3 * 3) / Divide Divide x by y 4/3 gives 1 (division of integers gives an integer). 4.0/3 or 4/3.0 gives 1.3333333333333333 // Floor Division Returns the floor of the quotient 4 // 3.0 gives 1.0 % Modulo Returns the remainder of the division 8%3 gives 2. -25.5%2.25 gives 1.5 . << Left Shift Shifts the bits of the number to the left by the number of bits specified. (Each number is represented in memory by bits or binary digits i.e. 0 and 1) 2 << 2 gives 8. - 2 is represented by 10 in bits. Left shifting by 2 bits gives 1000 which represents the decimal 8. >> Right Shift Shifts the bits of the number to the right by the number of bits specified. 11 >> 1 gives 5 - 11 is represented in bits by 1011 which when right shifted by 1 bit gives 101 which is nothing but decimal 5. & Bitwise AND Bitwise AND of the numbers 5 & 3 gives 1. | Bit-wise OR Bitwise OR of the numbers 5 | 3 gives 7 ^ Bit-wise XOR 5 ^ 3 gives 6 ~ Bit-wise invert The bit-wise inversion of x is -(x+1) ~5 gives -6. < Less Than Returns whether x is less than y. All comparison operators return 1 for true and 0 for false. This is equivalent to the special variables True and False respectively. Note the capitalization of these variables’ names. 5 < 3 gives 0 (i.e. False) and 3 < 5 gives 1 (i.e. True). Comparisons can be chained arbitrarily: 3 < 5 < 7 gives True. > Greater Than Returns whether x is greater than y 5 < 3 returns True. If both operands are numbers, they are first converted to a common type. Otherwise, it always returns False. <= Less Than or Equal To Returns whether x is less than or equal to y x = 3; y = 6; x <= y returns True. >= Greater Than or Equal To Returns whether x is greater than or equal to y x = 4; y = 3; x >= 3 returns True. == Equal To Compares if the objects are equal x = 2; y = 2; x == y returns True. x = ‘str’; y = ‘stR’; x == y returns False. x = ‘str’; y = ‘str’; x == y returns True. != Not Equal To Compares if the objects are not equal x = 2; y = 3; x != y returns True. not Boolean NOT If x is True, it returns False. If x is False, it returns True. x = True; not y returns False. and Boolean AND x and y returns False if x is False, else it returns evaluation of y x = False; y = True; x and y returns False since x is False. In this case, Python will not evaluate y since it knows that the value of the expression will has to be false (since x is False). This is called short-circuit evaluation. or Boolean OR If x is True, it returns True, else it returns evaluation of y x = True; y = False; x or y returns True. Short-circuit evaluation applies here as well.

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 than 2 + 3 * 4. As with everything else, the parentheses shold be used sensibly and should not be redundant (as in 2 + (3 + 4)).

Table 5.2. Operator Precedence

Operator                    Description
lambda               Lambda Expression
or                   Boolean OR
and                  Boolean AND
not x                Boolean NOT
in, not in           Membership tests
is, is not           Identity tests
<, <=, >, >=, !=, == Comparisons
|                    Bitwise OR
^                    Bitwise XOR
&                    Bitwise AND
<<, >>               Shifts
+, -                 Addition and subtraction
*, /, %              Multiplication, Division and Remainder
+x, -x               Positive, Negative
~x                   Bitwise NOT
**                   Exponentiation
x.attribute          Attribute reference
x[index]             Subscription
x[index:index]       Slicing
f(arguments ...)     Function call
(expressions, ...)   Binding or tuple display
[expressions, ...]   List display
{key:datum, ...}     Dictionary display
`expressions, ...`   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.

Order of Evaluation

By default, the operator precedence table decides which operators are evaluated before others. However, if you want to change the orer in which they are evaluated, you can use parentheses. For example, if you want addition to be evaluated before multiplication in an expression, then you can write something like (2 + 3) * 4.

Associativity

Operators are usually associated from left to right i.e. operators with same precedence are evaluated in a left to right manner. For example, 2 + 3 + 4 is evaluated as (2 + 3) + 4. Some operators like assignment operators have right to left associativity i.e. a = b = c is treated as a = (b = c).

Expressions

Using Expressions

Example 5.1. Using Expressions

#!/usr/bin/python
# Filename: expression.py

length = 5
breadth = 2

area = length * breadth
print 'Area is', area
print 'Perimeter is', 2 * (length + breadth)
Output
$ python expression.py
Area is 10
Perimeter is 14
How It Works

The length and breadth of the rectangle are stored in variables by the same name. We use these to calculate the area and perimieter of the rectangle with the help of expressions. We store the result of the expression length * breadth in the variable area and then print it using the print statement. In the second case, we directly use the value of the expression 2 * (length + breadth) in the print statement.

Also, notice how Python ‘pretty-prints’ the output. Even though we have not specified a space between ‘Area is’ and the variable area, Python puts it for us so that we get a clean nice output and the program is much more readable this way (since we don’t need to worry about spacing in the output). This is an example of how Python makes life easy for the programmer.

Summary

We have seen how to use operators, operands and expressions - these are the basic building blocks of any program. Next, we will see how to make use of these in our programs using statements.