Operators are specials symbols which perform certain arithmetic or logical operation on operands. Consider an example, 1+2 =3, here, 1 and 2 are called operands and + (plus) is the operator.
The operators can be categorized into 7 different category in python:
1. Arithmetic operator
2. Comparison ( or Relational) operator
3. Assignment operator
4. Logical operator
5. Bitwise operator
6. Membership operator
7. Identity operator.
Arithmetic operators
Arithmetic operators are used for performing arithmetic operations between two operands. It includes +(addition), – (subtraction), * (multiplication), / (division), % (reminder), // (floor division), ** ( exponent operators).
Operators | Description | Example |
+ (Addition) | use to add two operands | 3+4 (result 7) |
– (Subtraction) | use to subtract two operands | 3-4 (result -1) |
* (Multiplication) | use to multiply two operands | 3*4 (result 12) |
/ | use to divide one operand by another. It returns the quotient after division. Note: The divisor can not be 0 (zero) otherwise it throws ZeroDivisionError exception. | 3/4 (result 0.75)., 5/2 (result 2.5 ) Note: 3/0 results in ZeroDivisionError exception |
% (Reminder) | use to return the reminder after dividing first operand by second operand. | 3%4 ( result 3), 5%2 (result 1), 4%2 (result 0) and so on. |
** (Exponent Operator) | use to calculate power of values, generally first operand raised to the power of second operand.Like (xy) | 3**4 (equivalent to 34 = 81) |
// (Floor Division) | use to return the floor value of the quotient after dividing the two operands. | 3//4 (result 0) , 5//2 ( result 2) |
Comparison operator
Comparison operators are used to compare two values and return boolean value( either True or False) based on the comparison. It includes == (equals to), != (not equals to ) , < (less than), > (greater than), <= (less than or equal to), >= (greater than or equals to).
Operator | Description | Example (if a= 3 , b = 3, c = 5) |
== (Equals to) | returns True if the operands on both sides are equal otherwise it returns False. | a == b (result True), a == c (result False) |
!= (Not equals to) | returns True if the operands on both sides are not equal otherwise it returns False. | a != c (result True) , a != b (result False) |
< (Less than) | returns True if the operands on left sides is less than right side, otherwise it returns False. | a < c (result True), a < b (result False) |
> (Greater than) | returns True if the operands on left sides is greater than right side, otherwise it returns False. | c > a ( result True) , a > c ( result False), a > b ( result False) |
<= (Less than or equals to) | returns True if the operands on left sides is less than Or equals to right side, otherwise it returns False. | a <= c (result True), a <= b (result True), c <= a (result False) |
>=( Greater than or equals to) | returns True if the operands on left sides is greater than Or equals to right side, otherwise it returns False. | a >= b( result True), c >= a ( result True), a >= c (result False) |
Assignment operator
Assignment operator is used to assign the the value of right expression to left operand. It includes, = (equals), += (plus equals), -=(minus equals) , *= (multiply equals), /= (divide equals), %= ( remainder equals), **= (exponential value equals), //= (floor division equals). The left operand has to be a variable. It can not be a numeric value.For example a = 4, is correct, but 3 = 4.5 is incorrect and results in error.
Operator | Description | Example |
= (Equals) | It assigns value of the right expression to left operand. | c = 5, c will have 5 |
+= | It adds value of right operand to the value of left operand and assigns new value to left operands. For e.g. a += b is equivalent to a = a+b | if a = 3, and b = 4, then, a += b (result a = 7) |
-= | It subtracts value of right operand from the value of left operand and assigns new value to left operands. For e.g. a -= b is equivalent to a = a-b | if a = 3, and b = 4, then a -= b (result a = -1) |
*= | It multiplies value of left operand to the value of right operand and assigns new value to left operands. For e.g. a *= b is equivalent to a = a*b | if a = 3, and b = 4, then a *= b (result a = 12) |
/= | It divides value of left operand by the value of right operand and assigns new value to left operands. For e.g. a /= b is equivalent to a = a / b | if a = 3, and b = 4, then a /= b (result a = 0.75) |
%= | It divides value of left operand by the value of right operand and assigns new remainder value of division to left operands. For e.g. a /= b is equivalent to a = a / b | if a = 3, and b = 4, then a %= b (result a = 3), if |
**= | It raises power of value of right operand to the value of left operand and assigns new value to left operands. For e.g. a **= b is equivalent to a = a ** b | if a = 2, and b = 3, then a **= b (result a = 8) |
//= | It divides value of left operand by the value of right operand and assigns new floor division value to left operands. For e.g. a //= b is equivalent to a = a // b | if a = 5, and b = 2, then a //= b (result a = 2) |
Logical operator
Logical operators are used to evaluate two expression. These operators are used mostly in decision making.
It includes and, or and not operator.
Operator | Description | Example |
and | If both the expressions are true, then and will return true. Otherwise, it will return False. | If expression1 -> True, expression2 -> True, then, expression1 and expression2 , will result in True. Also, If a = 2, b =3, then a == 2 and b == 3, results in True |
or | If either of the expression is True then or will return True, otherwise it will return False. | If expression1 -> True, expression2 -> False, then, expression1 or expression2 , will result in True. Also, If a = 2, b =3, then a == 1 and b == 3, results in True |
not | It is used to flip the result of an expression. If expression1 is True, doing not (expression1) makes it False. | If a = True, not (a) , results in False. |
This operations follow boolean rule.
Operator | Operation | Result |
and | True and True | True |
and | True and False | False |
and | False and True | False |
or | True or True | True |
or | True or False | True |
or | False or True | True |
not | not (False) | True |
not | not (True) | False |
We have just compared the boolean values we can also compare two numeric values, and numeric values with and expression or string.
Number vs Number comparison
We might not use this type of scenario in day to day life, but it is worth wondering what happens when we compare two number with and and or operator .
For these comparison let’s open up python shell by typing python in command prompt or terminal. These concepts are tested in python version 3.7.
In the case of and operator, if we compare two numbers it will always return second number. In case of or operator it returns the first number.
For example
Python 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 21:26:53) [MSC v.1916 32 bit (Intel)]
on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> 3 and 4
4
>>> 44 and 3
3
>>> 3+5j and 4
4
>>> 4 and 3+5j
(3+5j)
>>> 3 or 4
3
>>> 44 or 3
44
Here in first two cases of and the second operand value(i.e. 4, 3 and (3+5j)) is returned, and in case of or first operand value is returned.
Number vs String comparison
1. and operator : It will always print the string value in case of and operator.
2. or operator: it return the first value(whatever it is) in case of or operator
Example:
>>> 3 and 'hello'
'hello'
>>> 'hello' and 3
3
>>> 3 or 'hello'
3
>>> 'hello' or 3
'hello'
Boolean value vs print statements
- and operator: if first statement is true it will execute second statement, if first is not true second statement is not executed.
- or operator : If the first statement is false it will print second statement, else if the first is True it will not execute second statement.
>>> False and print("hello world !")
False
>>> True and print("hello world !")
hello world !
>>> False or print("hello world !")
hello world !
>>> True or print("hello world !")
True
You might be wondering where can I use it. This kind of statement can be used to perform conditional rendering.
For example
>>> True and print("hello world !")
hello world !
This statement will only execute if first statement is True, in other words, this is equivalent to,
>>> if (True):
... print("hello world !")
...
hello world !
In case of True statement we can have some expression evaluating to True.
Bitwise operator
Bitwise operator performs bit by bit operation on the values of operands. To understand this we need to be able to think in terms of binary numbers.
It includes & (binary and), | (binary or) , ^ (binary xor), ~ (negation) , << (left shift), >> (right shift).
Operator | Description |
& ( binary and) | If both bits having same position on both side is equal to 1, then resulting bit will be 1 in the same place. Otherwise zero. |
| (binary or) | If both bits are zero then the resulting bit will also be 0 (zero), otherwise, the resulting bit will be 1. |
^ (binary xor) | if both bits are different (meaning 1 and 0, 0 and 1) then the resulting bit will be 1. Otherwise, the resulting bit will be 0 |
~ (negation) | it flips the bit value. If it is 0 it will result in 1 and if 1 it will result in 0. |
<< (left shift) | The left operand value is moved left by the number of bits present in the right operand. |
>> (right shift) | The left operand is moved right by the number of bits present in the right operand |
Example:
To test this let’s open up python shell.
In python binary is represented by starting zero followed by ‘b’ by ‘0b…’. For example. 0b111 = 7, 0b110 = 6. To convert number to binary we can use bin(number) e.g bin(7) , results in 0b111. To get number value of binary just type the binary in shell it will return equivalent numeric value. Now we have the basics lets do the operation.
Python 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 21:26:53) [MSC v.1916 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> bin(6)
'0b110'
>>> bin(7)
'0b111'
>>> 6 & 7
6
>>> 0b110 & 0b111
6
>>> 6 | 7
7
>>> 0b110 | 0b111
7
>>> 6 ^ 7
1
>>> 0b110 ^ 0b111
1
>>> ~ 6
-7
>>> ~ 0b110
-7
>>> 6 << 2
24
>>> 0b110 << 2
24
>>> 6 >> 2
1
>>> 0b110 >> 2
1
Membership operator
These operator are used to check whether a value exist in sequence data type(such as list, tuple, and sets). It includes in and not in operator
Operator | Description |
in | It evaluates to True in the value defined in left operand exist in the sequence data type on the right side. Otherwise it returns false. |
not in | It evaluates to True if there is no value (the value defined in left operand) in the sequence data type defined in right side. Otherwise it return False. |
For example
>>> list_values = [1,2,3,3]
>>> 2 in list_values
True
>>> 55 in list_values
False
>>> 33 not in list_values
True
>>> 2 not in list_values
False
>>> tuple_values = (1,2,3,4)
>>> 2 in tuple_values
True
>>> set_values = {1,2,3}
>>> 2 in set_values
True
Identity operator
This operator is used to compare whether both values are identical or not. It compares values based on id() of the value. In python each literals and variables have unique id assigned to them.
It includes is and is not
Operator | Description |
is | it evaluates to True if the reference at both side is same. |
is not | it evaluates to True if the reference pointed by both operands are not same. |
For example:
Note we can find id of a value using id() function. For example id(3), id(3.0).
>>> a = 'hi'
>>> b = 'hi'
>>> a is b
True
>>> c = '3'
>>> d = 3
>>> c is d
False
>>> 3 is 3
True
>>> 3 is 3.0
False
>>> id(3)
1888838784
>>> id(3.0)
18930928
>>> c is not d
True
Difference between == (equals to ) and is :
The difference between is and == is that == compares value of two operand and is compares id() of two values. As value 3 and 3.0 is save but they have different id so 3 == 3.0 returns True and 3 is 3.0 returns false.
For example,
>>> id (3)
1888838784
>>> id(3.0)
18930928
>>> 3 == 3.0
True
>>> 3 is 3.0
False
Operator precedence
We should know in case of multiple operator which operator will be evaluated at first. Following is the operator precedence table.
Operator | Description |
** | exponent operator is given priority over any other expression. |
~, +, – | after that negation, unary plus, and minus are given precedence. |
* , /, %, // | after that multiplication, division, remainder, and floor division operator is give precedence. |
+, – | after that addition and subtraction is give precedence |
>>, << | after that left swift and right shift |
& | binary and |
^ | | binary xor , and binary or |
<=, <, >, >= | comparison operator( less than equals,less than, greater than, greater than or equals) |
<>, == , != | equality operators |
=, %= , /= , //=,-=, +=, *= , **= | Assignment operators |
is , is not | identity operator |
in , not in | membership operator |
not, or , and | logical operator |