1.5: Operators and Expressions
- Page ID
- 20366
\( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \)
\( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)
\( \newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\)
( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\)
\( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\)
\( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\)
\( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\)
\( \newcommand{\Span}{\mathrm{span}}\)
\( \newcommand{\id}{\mathrm{id}}\)
\( \newcommand{\Span}{\mathrm{span}}\)
\( \newcommand{\kernel}{\mathrm{null}\,}\)
\( \newcommand{\range}{\mathrm{range}\,}\)
\( \newcommand{\RealPart}{\mathrm{Re}}\)
\( \newcommand{\ImaginaryPart}{\mathrm{Im}}\)
\( \newcommand{\Argument}{\mathrm{Arg}}\)
\( \newcommand{\norm}[1]{\| #1 \|}\)
\( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\)
\( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\AA}{\unicode[.8,0]{x212B}}\)
\( \newcommand{\vectorA}[1]{\vec{#1}} % arrow\)
\( \newcommand{\vectorAt}[1]{\vec{\text{#1}}} % arrow\)
\( \newcommand{\vectorB}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \)
\( \newcommand{\vectorC}[1]{\textbf{#1}} \)
\( \newcommand{\vectorD}[1]{\overrightarrow{#1}} \)
\( \newcommand{\vectorDt}[1]{\overrightarrow{\text{#1}}} \)
\( \newcommand{\vectE}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash{\mathbf {#1}}}} \)
\( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \)
\( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)
\(\newcommand{\avec}{\mathbf a}\) \(\newcommand{\bvec}{\mathbf b}\) \(\newcommand{\cvec}{\mathbf c}\) \(\newcommand{\dvec}{\mathbf d}\) \(\newcommand{\dtil}{\widetilde{\mathbf d}}\) \(\newcommand{\evec}{\mathbf e}\) \(\newcommand{\fvec}{\mathbf f}\) \(\newcommand{\nvec}{\mathbf n}\) \(\newcommand{\pvec}{\mathbf p}\) \(\newcommand{\qvec}{\mathbf q}\) \(\newcommand{\svec}{\mathbf s}\) \(\newcommand{\tvec}{\mathbf t}\) \(\newcommand{\uvec}{\mathbf u}\) \(\newcommand{\vvec}{\mathbf v}\) \(\newcommand{\wvec}{\mathbf w}\) \(\newcommand{\xvec}{\mathbf x}\) \(\newcommand{\yvec}{\mathbf y}\) \(\newcommand{\zvec}{\mathbf z}\) \(\newcommand{\rvec}{\mathbf r}\) \(\newcommand{\mvec}{\mathbf m}\) \(\newcommand{\zerovec}{\mathbf 0}\) \(\newcommand{\onevec}{\mathbf 1}\) \(\newcommand{\real}{\mathbb R}\) \(\newcommand{\twovec}[2]{\left[\begin{array}{r}#1 \\ #2 \end{array}\right]}\) \(\newcommand{\ctwovec}[2]{\left[\begin{array}{c}#1 \\ #2 \end{array}\right]}\) \(\newcommand{\threevec}[3]{\left[\begin{array}{r}#1 \\ #2 \\ #3 \end{array}\right]}\) \(\newcommand{\cthreevec}[3]{\left[\begin{array}{c}#1 \\ #2 \\ #3 \end{array}\right]}\) \(\newcommand{\fourvec}[4]{\left[\begin{array}{r}#1 \\ #2 \\ #3 \\ #4 \end{array}\right]}\) \(\newcommand{\cfourvec}[4]{\left[\begin{array}{c}#1 \\ #2 \\ #3 \\ #4 \end{array}\right]}\) \(\newcommand{\fivevec}[5]{\left[\begin{array}{r}#1 \\ #2 \\ #3 \\ #4 \\ #5 \\ \end{array}\right]}\) \(\newcommand{\cfivevec}[5]{\left[\begin{array}{c}#1 \\ #2 \\ #3 \\ #4 \\ #5 \\ \end{array}\right]}\) \(\newcommand{\mattwo}[4]{\left[\begin{array}{rr}#1 \amp #2 \\ #3 \amp #4 \\ \end{array}\right]}\) \(\newcommand{\laspan}[1]{\text{Span}\{#1\}}\) \(\newcommand{\bcal}{\cal B}\) \(\newcommand{\ccal}{\cal C}\) \(\newcommand{\scal}{\cal S}\) \(\newcommand{\wcal}{\cal W}\) \(\newcommand{\ecal}{\cal E}\) \(\newcommand{\coords}[2]{\left\{#1\right\}_{#2}}\) \(\newcommand{\gray}[1]{\color{gray}{#1}}\) \(\newcommand{\lgray}[1]{\color{lightgray}{#1}}\) \(\newcommand{\rank}{\operatorname{rank}}\) \(\newcommand{\row}{\text{Row}}\) \(\newcommand{\col}{\text{Col}}\) \(\renewcommand{\row}{\text{Row}}\) \(\newcommand{\nul}{\text{Nul}}\) \(\newcommand{\var}{\text{Var}}\) \(\newcommand{\corr}{\text{corr}}\) \(\newcommand{\len}[1]{\left|#1\right|}\) \(\newcommand{\bbar}{\overline{\bvec}}\) \(\newcommand{\bhat}{\widehat{\bvec}}\) \(\newcommand{\bperp}{\bvec^\perp}\) \(\newcommand{\xhat}{\widehat{\xvec}}\) \(\newcommand{\vhat}{\widehat{\vvec}}\) \(\newcommand{\uhat}{\widehat{\uvec}}\) \(\newcommand{\what}{\widehat{\wvec}}\) \(\newcommand{\Sighat}{\widehat{\Sigma}}\) \(\newcommand{\lt}{<}\) \(\newcommand{\gt}{>}\) \(\newcommand{\amp}{&}\) \(\definecolor{fillinmathshade}{gray}{0.9}\)Operators and Expressions
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 is called operands. In this case, 2
and 3
are the operands.
Operators
We will briefly take a look at the operators and their usage.
Note that 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
>>>
Here is a quick overview of the available operators:
+
(plus)- Adds two objects
3 + 5
gives8
.'a' + 'b'
gives'ab'
.
-
(minus)- Gives the subtraction of one number from the other; if the first operand is absent it is assumed to be zero.
-5.2
gives a negative number and50 - 24
gives26
.
*
(multiply)- Gives the multiplication of the two numbers or returns the string repeated that many times.
2 * 3
gives6
.'la' * 3
gives'lalala'
.
**
(power)- Returns x to the power of y
3 ** 4
gives81
(i.e.3 * 3 * 3 * 3
)
/
(divide)- Divide x by y
13 / 3
gives4.333333333333333
//
(divide and floor)- Divide x by y and round the answer down to the nearest integer value. Note that if one of the values is a float, you'll get back a float.
13 // 3
gives4
-13 // 3
gives-5
9//1.81
gives4.0
%
(modulo)- Returns the remainder of the division
13 % 3
gives1
.-25.5 % 2.25
gives1.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
gives8
.2
is represented by10
in bits.- Left shifting by 2 bits gives
1000
which represents the decimal8
.
>>
(right shift)- Shifts the bits of the number to the right by the number of bits specified.
11 >> 1
gives5
.11
is represented in bits by1011
which when right shifted by 1 bit gives101
which is the decimal5
.
&
(bit-wise AND)- Bit-wise AND of the numbers
5 & 3
gives1
.
|
(bit-wise OR)- Bitwise OR of the numbers
5 | 3
gives7
^
(bit-wise XOR)- Bitwise XOR of the numbers
5 ^ 3
gives6
~
(bit-wise invert)- The bit-wise inversion of x is -(x+1)
~5
gives-6
. More details at http://stackoverflow.com/a/11810203
<
(less than)- Returns whether x is less than y. All comparison operators return
True
orFalse
. Note the capitalization of these names. 5 < 3
givesFalse
and3 < 5
givesTrue
.- Comparisons can be chained arbitrarily:
3 < 5 < 7
givesTrue
.
- Returns whether x is less than y. All comparison operators return
>
(greater than)- Returns whether x is greater than y
5 > 3
returnsTrue
. If both operands are numbers, they are first converted to a common type. Otherwise, it always returnsFalse
.
<=
(less than or equal to)- Returns whether x is less than or equal to y
x = 3; y = 6; x <= y
returnsTrue
>=
(greater than or equal to)- Returns whether x is greater than or equal to y
x = 4; y = 3; x >= 3
returnsTrue
==
(equal to)- Compares if the objects are equal
x = 2; y = 2; x == y
returnsTrue
x = 'str'; y = 'stR'; x == y
returnsFalse
x = 'str'; y = 'str'; x == y
returnsTrue
!=
(not equal to)- Compares if the objects are not equal
x = 2; y = 3; x != y
returnsTrue
not
(boolean NOT)- If x is
True
, it returnsFalse
. If x isFalse
, it returnsTrue
. x = True; not x
returnsFalse
.
- If x is
and
(boolean AND)x and y
returnsFalse
if x isFalse
, else it returns evaluation of yx = False; y = True; x and y
returnsFalse
since x is False. In this case, Python will not evaluate y since it knows that the left hand side of the 'and' expression isFalse
which implies that the whole expression will beFalse
irrespective of the other values. 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
returnsTrue
. Short-circuit evaluation applies here as well.
- If x is
Shortcut for math operation and assignment
It is common to run a math operation on a variable and then assign the result of the operation back to the variable, hence there is a shortcut for such expressions:
a = 2
a = a * 3
can be written as:
a = 2
a *= 3
Notice that var = var operation expression
becomes var operation= expression
.
Evaluation Order
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 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 and expressions lower in the table before the ones listed higher in the table.
The following table, taken from the Python reference manual, is provided for the sake of completeness. It is far better to use parentheses to group operators and operands appropriately in order to explicitly specify the precedence. This makes the program more readable. See Changing the Order of Evaluation below for details.
lambda
: Lambda Expressionif - else
: Conditional expressionor
: Boolean ORand
: Boolean ANDnot x
: Boolean NOTin, not in, is, is not, <, <=, >, >=, !=, ==
: Comparisons, including membership tests and identity tests|
: Bitwise OR^
: Bitwise XOR&
: Bitwise AND<<, >>
: Shifts+, -
: Addition and subtraction*, /, //, %
: Multiplication, Division, Floor Division and Remainder+x, -x, ~x
: Positive, Negative, bitwise NOT**
: Exponentiationx[index], x[index:index], x(arguments...), x.attribute
: Subscription, slicing, call, attribute reference(expressions...), [expressions...], {key: value...}, {expressions...}
: Binding or tuple display, list display, dictionary display, set display
The operators which we have not already come across will be explained in later chapters.
Operators with the same precedence are listed in the same row in the above table. For example, +
and -
have the same precedence.
Changing the Order Of Evaluation
To make the expressions more readable, we can use parentheses. For example, 2 + (3 * 4)
is definitely easier to understand than 2 + 3 * 4
which requires knowledge of the operator precedences. As with everything else, the parentheses should be used reasonably (do not overdo it) and should not be redundant, as in (2 + (3 * 4))
.
There is an additional advantage to using parentheses - it helps us to change the order of evaluation. 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. This means that operators with the same precedence are evaluated in a left to right manner. For example, 2 + 3 + 4
is evaluated as (2 + 3) + 4
.
Expressions
Example (save as 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 perimeter 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
function. In the second case, we directly use the value of the expression 2 * (length + breadth)
in the print function.
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 strings we use for 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.