Python 3 Operators: Arithmetic, Comparison, Logical and More
What Are Operators in Python?
Operators are special symbols in Python that carry out arithmetic or logical computation. The value that the operator operates on is called the operand.
For example:
>>> a = 10
>>> b = 20
>>> a + b
30
In this case, the +
operator adds the operands a
and b
together. An operand can be either a literal value or a variable that references an object:
>>> a = 10
>>> b = 20
>>> a + b - 5
25
A sequence of operands and operators, like a + b - 5
, is called an expression. Python supports many operators for combining data objects into expressions.
Types of Operator
Python language supports the following types of operators:
- Arithmetic Operators
- Comparison (Relational) Operators
- Assignment Operators
- Logical Operators
- Bitwise Operators
- Membership Operators
- Identity Operators
Let us have a look at all the operators one by one.
Arithmetic Operators
Assume variable a
holds the value 10 and variable b
holds the value 21, then
Operator | Description | Example |
---|---|---|
+ Addition | Adds values on either side of the operator. | a + b = 31 |
- Subtraction | Subtracts right hand operand from left hand operand. | a – b = -11 |
* Multiplication | Multiplies values on either side of the operator | a * b = 210 |
/ Division | Divides left hand operand by right hand operand | b / a = 2.1 |
% Modulus | Divides left hand operand by right hand operand and returns remainder | b % a = 1 |
** Exponent | Performs exponential (power) calculation on operators | a**b =10 to the power 20 |
// | Floor Division – The division of operands where the result is the quotient in which the digits after the decimal point are removed. But if one of the operands is negative, the result is floored, i.e., rounded away from zero (towards negative infinity): | 9//2 = 4 and 9.0//2.0 = 4.0, -11//3 = -4, -11.0//3 = -4.0 |
Here are some examples of these operators in use:
>>> a = 4
>>> b = 3
>>> +a
4
>>> -b
-3
>>> a + b
7
>>> a - b
1
>>> a * b
12
>>> a / b
1.3333333333333333
>>> a % b
1
>>> a ** b
64
The result of standard division (/
) is always a float
, even if the dividend is evenly divisible by the divisor:
>>> 10 / 5
2.0
>>> type(10 / 5)
<class 'float'>
When the result of floor division (//
) is positive, it is as though the fractional portion is truncated off, leaving only the integer portion. When the result is negative, the result is rounded down to the next smallest (greater negative) integer:
>>> 10 / 4
2.5
>>> 10 // 4
2
>>> 10 // -4
-3
>>> -10 // 4
-3
>>> -10 // -4
2
Note, by the way, that in a REPL session, you can display the value of an expression by just typing it in at the >>>
prompt without print()
, the same as you can with a literal value or variable:
>>> 25
25
>>> x = 4
>>> y = 6
>>> x
4
>>> y
6
>>> x * 25 + y
106
Comparison Operators
These operators compare the values on either side of them and decide the relation among them. They are also called Relational operators.
Assume variable a
holds the value 10 and variable b
holds the value 20, then
Operator | Description | Example |
---|---|---|
== | If the values of two operands are equal, then the condition becomes true. | (a == b) is not true. |
!= | If values of two operands are not equal, then condition becomes true. | (a!= b) is true. |
> | If the value of left operand is greater than the value of right operand, then condition becomes true. | (a > b) is not true. |
< | If the value of left operand is less than the value of right operand, then condition becomes true. | (a < b) is true. |
>= | If the value of left operand is greater than or equal to the value of right operand, then condition becomes true. | (a >= b) is not true. |
<= | If the value of left operand is less than or equal to the value of right operand, then condition becomes true. | (a <= b) is true. |
Here are examples of the comparison operators in use:
>>> a = 10
>>> b = 20
>>> a == b
False
>>> a != b
True
>>> a <= b
True
>>> a >= b
False
>>> a = 30
>>> b = 30
>>> a == b
True
>>> a <= b
True
>>> a >= b
True
Assignment Operators
Theassignment operators in Python are used to store data into a variable. We’ve already used the most common assingment operator (=
), but there are many more of them.
Assume variable a
holds the value 10 and variable b
holds the value 20, then
Operator | Description | Example |
---|---|---|
= | Assigns values from right side operands to left side operand | c = a + b assigns value of a + b into c |
+= Add AND | It adds right operand to the left operand and assign the result to left operand | c += a is equivalent to c = c + a |
-= Subtract AND | It subtracts right operand from the left operand and assign the result to left operand | c -= a is equivalent to c = c – a |
*= Multiply AND | It multiplies right operand with the left operand and assign the result to left operand | c *= a is equivalent to c = c * a |
/= Divide AND | It divides left operand with the right operand and assign the result to left operand | c /= a is equivalent to c = c / ac /= a is equivalent to c = c / a |
%= Modulus AND | It takes modulus using two operands and assign the result to left operand | c %= a is equivalent to c = c % a |
**= Exponent AND | Performs exponential (power) calculation on operators and assign value to the left operand | c **= a is equivalent to c = c ** a |
//= Floor Division | It performs floor division on operators and assign value to the left operand | c //= a is equivalent to c = c // a |
Bitwise Operators
Bitwise operators treat operands as sequences of binary digits and operate on them bit by bit. The following operators are supported:
Operator | Example | Meaning | Result |
---|---|---|---|
& | a & b | bitwise AND | Each bit position in the result is the logical AND of the bits in the corresponding position of the operands. (1 if both are 1 , otherwise 0 .) |
| | a | b | bitwise OR | Each bit position in the result is the logical OR of the bits in the corresponding position of the operands. (1 if either is 1 , otherwise 0 .) |
~ | ~a | bitwise negation | Each bit position in the result is the logical negation of the bit in the corresponding position of the operand. (1 if 0 , 0 if 1 .) |
^ | a ^ b | bitwise XOR (exclusive OR) | Each bit position in the result is the logical XOR of the bits in the corresponding position of the operands. (1 if the bits in the operands are different, 0 if they are the same.) |
>> | a >> n | Shift right n places | Each bit is shifted right n places. |
<< | a << n | Shift left n places | Each bit is shifted left n places. |
Here are some examples:
>>> '0b{:04b}'.format(0b1100 & 0b1010)
'0b1000'
>>> '0b{:04b}'.format(0b1100 | 0b1010)
'0b1110'
>>> '0b{:04b}'.format(0b1100 ^ 0b1010)
'0b0110'
>>> '0b{:04b}'.format(0b1100 >> 2)
'0b0011'
>>> '0b{:04b}'.format(0b0011 << 2)
'0b1100'
Note: The purpose of the
'0b{:04b}'.format()
is to format the numeric output of the bitwise operations, to make them easier to read. You will see theformat()
method in much more detail later. For now, just pay attention to the operands of the bitwise operations, and the results.
Logical Operators
There are three logical operators that are used to compare values. They evaluate expressions down to Boolean values, returning either True
or False
. These operators are and
, or
, and not
and are defined in the table below.
Operator | What it means | What it looks like |
---|---|---|
and | True if both are true | x and y |
or | True if at least one is true | x or y |
not | True only if false | not x |
To understand how logical operators work, let’s evaluate three expressions:
print((9 > 7) and (2 < 4)) # Both original expressions are True
print((8 == 8) or (6 != 6)) # One original expression is True
print(not(3 <= 1)) # The original expression is False
The result will be as follows:
True
True
True
Identity Operators
Python provides two operators, is
and is not
, that determine whether the given operands have the same identity—that is, refer to the same object. This is not the same thing as equality, which means the two operands refer to objects that contain the same data but are not necessarily the same object.
Operator | Description | Example |
---|---|---|
is | Evaluates to true if the variables on either side of the operator point to the same object and false otherwise. | x is y, here is results in 1 if id(x) equals id(y). |
is not | Evaluates to false if the variables on either side of the operator point to the same object and true otherwise. | x is not y, here is notresults in 1 if id(x) is not equal to id(y). |
Here is an example of two object that are equal but not identical:
>>> x = 1001
>>> y = 1000 + 1
>>> print(x, y)
1001 1001
>>> x == y
True
>>> x is y
False
Here, x
and y
both refer to objects whose value is 1001
. They are equal. But they do not reference the same object, as you can verify:
>>> id(x)
60307920
>>> id(y)
60307936
x
and y
do not have the same identity, and x is y
returns False
.
You saw previously that when you make an assignment like x = y
, Python merely creates a second reference to the same object, and that you could confirm that fact with the id()
function. You can also confirm it using the is
operator:
>>> a = 'I am a string'
>>> b = a
>>> id(a)
55993992
>>> id(b)
55993992
>>> a is b
True
>>> a == b
True
In this case, since a
and b
reference the same object, it stands to reason that a
and b
would be equal as well.
Unsurprisingly, the opposite of is
is is not
:
>>> x = 10
>>> y = 20
>>> x is not y
True
Membership Operators
Python’s membership operators test for membership in a sequence, such as strings, lists, or tuples. There are two membership operators as explained below
Operator | Description | Example |
---|---|---|
in | Evaluates to true if it finds a variable in the specified sequence and false otherwise. | x in y, here in results in a 1 if x is a member of sequence y. |
not in | Evaluates to true if it does not finds a variable in the specified sequence and false otherwise. | x not in y, here not in results in a 1 if x is not a member of sequence y. |
Operators Precedence
The following table lists all operators from highest precedence to the lowest.
Operator | Description |
---|---|
() | Parentheses (grouping) |
f (args…) | Function call |
x [index:index] | Slicing |
x [index] | Subscription |
x.attribute | Attribute reference |
** | Exponentiation |
~x | Bitwise not |
+x , –x | Positive, negative |
*, /, % | Multiplication, division, remainder |
+, – | Addition, subtraction |
<<, >> | Bitwise shifts |
& | Bitwise AND |
^ | Bitwise XOR |
| | Bitwise OR |
in, not in, is, is not, <, <=, >, >=, <>, !=, == | Comparisons, membership, identity |
not x | Boolean NOT |
and | Boolean AND |
or | Boolean OR |
lambda | Lambda expression |
Highest precedence at top, lowest at bottom.
Operators in the same box evaluate left to right.
Conclusion
In this tutorial, you learned about the diverse operators Python supports to combine objects into expressions.