Operators
Python supports several operators. Here, we review some of the key ones.
We use the arithmetic operators to do simple math on two variables or literals. Be sure to only try to use arithmetic operators on like types. For example, if you try to add a string value to a integer (3 + “ is a number”) you will get an error.
+ Addition
Adds the left value to the right:
>>> lvariable = 5
>>> sum = lvariable + 3
>>> sum
8
− Subtraction
Subtracts the right value from left:
>>> lvariable = 5
>>> difference = lvariable - 3
>>> difference
2
* Multiplication
Multiplies left value by right:
>>> lvariable = 5
>>> product = lvariable * 3
>>> product
15
/ Division
Divides left value by right. Integer divided by integer returns an integer. Right-side value can not be zero:
>>> quotient = 5 / 3 # integer/integer
>>> quotient
1
>>> quotient = 5.2 / 3.1 # float/float
>>> quotient
1.6774193548387097
>>> quotient = 3.14159 / 7 # float/integer
>>> quotient
0.44879857142857144
>>> quotient = 7 / 3.14159 # integer/float
>>> quotient
2.2281710853421357
>>> quotient = 5 / 0
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ZeroDivisionError: integer division or modulo by zero
% Modulus
Divides left value by right and returns the remainder:
>>> remainder = 5 % 3
>>> remainder
2
>>> remainder = 3 % 5
>>> remainder
3
** Exponent
Left value raised to the power of the right:
>>> exp = 2 ** 3
>>> exp
8
>>> exp = 2.1 ** 3
>>> exp
9.261000000000001
// Floor Division
Division, but with the decimal values rounded down to the nearest integer:
>>> quotient = 5.2 // 3.1
>>> quotient
1.0
When we want to compare two values to each other, as in equality (a is equal to b), we use comparison operators. Unlike many other programming languages Python comparison operators may differ.
In the following examples, assume the following:
a = 5
b = 3
==
Checks to see if left variable is equal to right. Please note that when using floating point numbers (floats) that there will be times that the calculations do not act as you might expect due to the way floating point numbers are stored in Python. When you need precise calculations, use the decimal library:
>>> print(a == b)
False
>>> test = 1.1+2.2
>>> test == 3.3
False # test is actually 3.3000000000000003
== (Strings)
Comparison of strings, lists, and other objects is very similar to that of numbers:
Str1 = "This is a test"
Str2 = "This was a test"
Str1 == Str2
False
Lst1 = [1,2,3,4]
Lst2 = Lst1
Lst2 == Lst1
True
!=
Checks to see if left variable is NOT equal to right (3.x and 2.x):
Python 2.x
>>> print(a != b)
True
Python 3.x
>>> print(a != b)
True
<>
Checks to see if left variable is NOT equal to right (2.x only):
Python 2.x
>>> print(a <> b)
True
Python 3.x (use !=)
>>> print(a <> b)
File "<stdin>", line 1
print(a <> b)
^
SyntaxError: invalid syntax
>
Checks to see if left variable is greater than right:
>>> print(a > b)
True
<
Checks to see if left variable is less than right:
>>> print(a < b)
False
>=
Checks to see if left variable is greater than or equal to right:
>>> print(a >= b)
True
<=
Checks to see if left variable is less than or equal to right:
>>> print(a <= b)
False
Assignment operators, as we have seen earlier, assigns and/or modifies a value to a variable.
=
Assignment operator. Assigns the value on right to variable on left:
>>> a = 3
>>> a
3
+=
Add and assign or increment operator. Adds value on right to left variable:
>>> a = 3
>>> a += 3
>>> a
6
−=
Subtract and assign or decrement operator. Subtracts value on right from left variable:
>>> a = 3
>>> a -= 2
>>> a
1
*=
Multiply and assign. Multiplies right value to left value:
>>> a = 3
>>> a *= 2
>>> a
6
/=
Divide and assign. Divides right value from left value:
>>> a = 3
>>> a /= 2.0
>>> a
1.5
%=
Modulus and assign:
>>> a = 3
>>> a %= 2
>>> a
1
**=
Exponent and assign:
>>> a = 3
>>> a **= 2
>>> a
9
//=
Floor Division and assign:
>>> a = 5.0
>>> a //= 3.0
>>> a
1.0
Python provides three operators for logical operations: and, or and not. These operators allow us to compare two values without having to rely on normal equality considerations. You could think of logical operators as sort of a high level binary evaluation.
Logical AND – if both values are True (or in many cases, nonzero), then returns a true value:
a = 0
b = 8
if (a and b):
print 'true'
else:
print 'false'
False
Logical OR – if either value is True, returns a true value:
a = 0
b = 8
if (a or b):
print 'true'
else:
print 'false'
True
Logical NOT – reverses the operator. True becomes False and False becomes True:
a = 0
b = 8
if not(a and b):
print 'true'
else:
print 'false'
True
Membership and Identity Operators
We use membership operators to test to see if a particular value is a member of (or is included in) a particular object like a list or dictionary. The identity operators check to see if the two objects are the same.
In
Returns True if x is in y:
>>> a = "This is the time"
>>> 'is' in a
True
>>> lst = [1,2,4,7,9]
>>> 2 in lst
True
>>> 8 in lst
False
not in
Returns True if x is NOT in y:
>>> a = "This is the time"
>>> 'frog' not in a
True
is
Returns True if variables on each side refers to the same object:
>>> c = list(['a','b','c'])
>>> d = c
>>> c is d
True
is not
Returns False if variables on each side refers to the same object:
>>> c = list(['a','b','c'])
>>> d = c
>>> c is not d
False
These operators perform bit by bit operations on binary values.
Binary numbers consist of 1s and 0s called bits. In a 4-bit binary number, the value will range from 0 to 15. In an 8-bit number, the value will range from 0 to 255. Each bit position has a value starting from right to left. A 1 in any position gets counted to make a standard decimal number. For a 4-bit number, the positions are 1,2,4,8. It is easy to see that the value for each position is doubled.
0000 0
0001 1
0010 2
0011 3
0100 4
…
In the following examples, assume the following:
a = 00011000 (24)
b = 00001000 (8)
&
Binary AND
Compares bit by bit the two values; if the bits are both 1 in any given position, then the result is 1 for that bit position:
>>> a & b
8 (00001000)
00011000
00001000
Equals
00001000 (8)
|
Binary OR
Compares bit by bit the two values and if either of the bits are 1 in any given position, then the result is 1 for that bit position:
>>> a | b
24 (00011000)
00011000
00001000
Equals
00011000 (24)
^
Binary XOR.
Compares bit by bit the two values and if either of the bits are 1 but not both bits, then the result is 1 for that bit position:
>>> a ^ b
16 (00010000)
00011000
00001000
Equals
00010000 (16)
∼
Binary Ones complement.
Ones complement is defined as the value that is obtained by inverting all the bits in the number. This then behaves like a negative value of the original value in some arithmetic operations:
a = 24 (00011000)
>>> ∼a
-25
(11100111)
<<
Binary Shift Left.
Shifts all bits to the left. Zeros are inserted at the right side:
>>> a << 2
96 (00011000 Shift Left 2 = 01100000 = 64 + 32 = 96)
>>
Binary Shift Right.
Shifts all bits to the right by x positions. Zeros are inserted at the left side:
>>> a >> 2
6 (00011000 Shift Right 2 = 00000110 = 2 + 4 = 6)
Precedence of operators is the order that the various operators are processed in calculations.
For example: If the calculation is 3 + 5 * 4 + 6, the answer would be 29. Multiplication takes precidence over addition, so the formula breaks down to 20 + 9 (5 * 4) + (3 + 6).
The precedence of evaluation is always overridden by the use of parentheses:
(3 + 5) * (4 + 6) = 112
3+5*4+10 = 33 (3 + 20 (5*4) + 10)
The following list shows precedence of the operators from lowest to highest: