Python Operators – A detailed guide
|In this Python article, we will learn about the different types of operators, operands and how we use them in python.
1. Operators and Operands
Operators are the signs we use in equations to perform a specific task and the object on which the task or calculation is being performed are known as operands.
Example: x + y * z
In the above example +
, *
are the operators which are used to do two task addition and multiplication whereas x,y, z
are operands on which the task is being performed.
Note: Operands are basically identifiers
In Python we have following types of operators :
- Arithmetic operators
- Relational operators or Comparison operator
- Logical operators
- Bitwise operators
- Assignment operators
- Identity operators
- Membership operators
Let’s discuss these operators in detail with examples.
2. Arithmetic operators
To do a basic arithmetic operation like addition, subtraction, multiplication, division etc. python provides operators. Each of these operators is a binary operator i.e it needs two operands to calculate the result.
Symbol | Name | Example |
---|---|---|
+ | addition | 2.0 + 8.2 return: 10.2 |
– | subtraction | 2.0 – 8.2 return: -6.2 |
* | multiplication | 2.0 * 8.2 return: 16.4 |
/ | division | 60 / 5 return: 12.0 |
% | Modulus | 73 % 5 return: 3 |
** | Exponentiation | 3**2 return: 9 |
// | floor division | 61 // 5 return: 12 |
2.1. Addition (+)
+
is used to add two values and return their sum.
Example :
>>> 6 + 5 11 >>> 3.0 + 8.8 12.0 >>> 3 + 4.22 7.22 >>> 4.2 + 5 9.2
2.2. Subtraction (-)
-
is used to subtract the value of right operand from left operand.
Example :
>>> 6 - 5 1 >>> 5 - 6 -1 >>> 2.0 - 8.2 -6.199999999999999 >>> 8.2 - 2 6.199999999999999 >>> 8 - 2.5 5.5
2.3. Multiplication (*)
*
is used to multiply the values of its operands does not matter in which order.
Example :
>>> 3 * 5 15 >>> -3 * 5 -15 >>> -3.0 * -5.0 15.0 >>> 3.0 * 5 15.0
2.4. Division (/)
/
is used to divides the value of left operand with the value of right operand and returns a float value
Example :
>>> 60 / 5 12.0 >>> 8.2 / 2.0 4.1 >>> -50 / 5.0 -10.0 >>> -50.0/-5 10.0
2.5. Modulus (%)
%
is used to divide the two operands and return the remainder
Example :
>>> 60 % 5 0 >>> 73 % 5 3 >>> -73 % 5 2 >>> 73.0 % 5 3.0
2.6. Floor Division (//)
//
is used to divide the operator and return the quotient. If both the operands are integer data type then it will remove the value after the decimal and if one of the operands is negative then the value is rounded away from zero that means towards negative infinity.
Example :
>>> 61 // 5 12 >>> 8.2 // 2.0 4.0 >>> -8.2 // 2 -5.0
2.7. Exponentiation (**)
**
is used to return the power of a number. The left operand is the base and right operand is the power we need to raise. Negative power means the inverse of the base as 2 to the power -2 is 1/2*2
Example :
>>> 3 ** 2 9 >>> 2 ** 3 8 >>> -2 ** 3 -8 >>> 2 ** -3 0.125
Let’s implement an example with all arithmetic operations and see how work in python:
a = 12 b = 3 print("Addition", a + b, sep=": ") print("\nSubtraction", a - b, sep=": ") print("\nMultiplication", a * b, sep=": ") print("\nExponential", a ** b, sep=": ") a = -12 print("\nModulus", a % b, sep=": ") print("\nDivision", a / b, sep=": ") print("\nFloor Division", a // b, sep=": ")
Output Addition : 15 Subtraction: 9 Multiplication: 36 Exponential: 1728 Modulus: 0 Division: -4.0 Floor Division: -4
3. Relational Operator
Relational refers to the relationship that operands can have with one another. So we can simply say that we are comparing operands that’s why relational operators are also known as comparison operators. They are used to compare two values and the result is always logical i.e either True or False.
Symbol | Name | Example |
---|---|---|
== | equality | 6 == 5 return: False |
< | less than | 6 < 5 return: False |
<= | less than or equal to | 6 <= 5 return: False |
> | greater than | 6 > 5 return: True |
>= | greater than or equal to | 6 >= 5 return: True |
!= | Not equal to | 6 != 5 return: True |
3.1. equality (==)
==
is used to compare the values, if both values are equal then it returns the boolean True otherwise False
Example :
>>> 7 == 10 False >>> 10 == -10 False >>> 7 == 7 True
3.2. less than (<)
<
is used to compare the values, if left is less than right then it returns the boolean True otherwise False
Example :
>>> 7 < 10 True >>> 10 < 10 False >>> 12 < 10 False
3.3. less than or equal to (<=)
<=
is used to compare the values, if left is less than or equal to right then it returns the boolean True otherwise False
Example :
>>> 7 <= 10 True >>> 10 <= 10 True >>> 12 <= 10 False
3.4. greater than (>)
>
is used to compare two values, if left is greater than right then it returns the boolean True otherwise False.
Example :
>>> 7 > 10 False >>> 10 > 10 False >>> 12 > 10 True
3.5. greater than or equal to (>=)
>=
is used to compare values, if left is greater than or equal to right then it returns the boolean True otherwise False.
Example :
>>> 7 >= 10 False >>> 10 >= 10 True >>> 12 >= 10 True
3.6. not equal to (!=)
!=
is used to compare values, if both values are not equal then it returns the boolean True otherwise False.
Example :
>>> 7 != 10 True >>> 10 != 10 False
Note : <> is similar to not equal to but it is removed from python3
Let’s implement all relational operators in a single python program and see how relational operators work:
a = 12 b = 3 print("Equality", a == b, sep=": ") print("\nLess than", a < b, sep=": ") print("\nLess than or equal to", a <= b, sep=": ") print("\nGreater than", a > b, sep=": ") print("\nGreater than equal to", a >= b, sep=": ") print("\nNot equal to", a != b, sep=": ")
Output Equality: False Less than: False Less than or equal to: False Greater than: True Greater than equal to: True Not equal to: True
4. Logical Operators
The logical operator is used to connect to relational or logical expression, the result of such an operation is always logical i.e. either True or False.
Symbol | Name | Example |
---|---|---|
and | Logical AND | True and False return: False |
or | Logical OR | True or False return: True |
not | Logical NOT | not True return: False |
4.1. Logical AND (and)
The output of logical AND is True if it’s both the operands are true else False. We can summarize the statement using the table below-
Expression | Output |
---|---|
True and False | False |
False and True | False |
True and True | True |
False and False | False |
4.2. Logical OR (or)
The output of Logical OR operation is False if both its operands are false else True. We can summarize the statement in the table below
Expression | Output |
---|---|
True or False | True |
False or True | True |
True or True | True |
False or False | False |
4.3. Logical NOT (not)
The output of the Logical operator is always the opposite of operand. Let’s summarize the above statement in the table below
Expression | Output |
---|---|
not True | False |
not False | True |
Let’s understand how these operators work in python:
a = True b = False print("Logical AND ", a and b, sep=": ") print("Logical OR ", a or b, sep=": ") print("Logical NOT ", not b, sep=": ")
Output Logical AND : False Logical OR : True Logical NOT : True
5. Bitwise Operators
Bitwise operators are used to comparing binary numbers. First, the number is converted into binary then the calculation is performed on bits and then the result is again converted to the decimal format.
Note: Binary numbers are consist of 0 and 1
Symbol | Name | Examples |
---|---|---|
& | Bitwise AND | x & y |
| | Bitwise OR | x | y |
^ | Bitwise XOR | x ^ y |
~ | Bitwise NOT | ~ x |
>> | Bitwise right shift | x >> |
<< | Bitwise left shift | x << |
5.1. Bitwise AND (&)
Bitwise AND is similar to Logical AND but instead of True and False here we compare the bits 0 and 1
Note : 0 is same as False and 1 is same as True
The output of Bitwise AND is 1 if it’s both the bits are 1 else we change the bit into 0. We can summarize the statement using the table below
Expression | Output |
---|---|
1 & 0 | 0 |
0 & 1 | 0 |
1 & 1 | 1 |
0 & 0 | 0 |
5.2. Bitwise OR (|)
Bitwise OR is similar to Logical OR, where the output is 0 if both bits are 0 else the bit is changed to 1. We can summarize the statement in the table below
Expression | Output |
---|---|
1 | 0 | 1 |
0 | 1 | 1 |
1 | 1 | 1 |
0 | 0 | 0 |
5.3. Bitwise XOR (^)
The output of bitwise XOR is 1 if only one of the bit is 1. We can summarize or understand the statement in the table below
Expression | Output |
---|---|
1 ^ 0 | 1 |
0 ^ 1 | 1 |
1 ^ 1 | 0 |
0 ^ 0 | 0 |
5.4. Bitwise NOT (~)
Bitwise NOT is similar to Logical NOT, where the output is the reverse of the bit. Let’s summarize the statement by the table below
Expression | Output |
---|---|
~ 0 | 1 |
~ 1 | 0 |
Remember: NOT will reverse the sign bit as well example if your decimal value is positive it will become negative and vice-versa.Let’s understand by checking out the code below
5.5. Bitwise right shift (>>)
>>
shifts the bit to right and the rightmost bit falls off and in the leftmost bit, we add a 0 bit. Right operand tells us the no. of the bit we need to shift.
Remember : We always consider 8-bit
Example : 13 >> 2
- 13 is in the binary format is written as 0000 1101
- Now when we will right-shift the bits by 2, then the right-most bit 01 will fall off
- And we will add 00 in the front
- So it will become 0000 0011 which in decimal format is 3.
5.6. Bitwise left shift (<<)
<<
shifts the bit to left and the leftmost bit falls off and in the rightmost bit, we add 0 bit. Right operand tells us the no. of the bit we need to shift.
Example : 13 << 2
- 13 is in the binary format is written as 0000 1101
- Now when we will left-shift the bits by 2, then the left-most bit will fall off.
- And we will add 00 in the back
- So it will become 0011 0100 which in decimal format is 52
Let’s understand how these operators work in python:
a = 22 b = 5 print("Bitwise AND", a & b, sep=": ") print("Bitwise OR", a | b, sep=": ") print("Bitwise XOR", a ^ b, sep=": ") print("Bitwise NOT", ~a, sep=": ") print("Bitwise Right Shift", a >> 2, sep=": ") print("Bitwise Right Shift", a << 2, sep=": ")
Output Bitwise AND: 4 Bitwise OR: 23 Bitwise XOR: 19 Bitwise NOT: -23 Bitwise Right Shift: 5 Bitwise Right Shift: 88
6. Assignment Operators (+= , -= …)
An assignment operator is used to assign the value of the expression on the right-hand side to the variable on the left-hand side.
Symbol | Same as | Example |
---|---|---|
= | x = 5 | x = 5 |
+= | x = x + 5 | x += 5 |
-= | x = x – 5 | x -= 5 |
*= | x = x * 5 | x *= 5 |
/= | x = x / 5 | x /= 5 |
%= | x = x % 5 | x %= 5 |
**= | x = x ** 5 | x **= 5 |
//= | x = x // 5 | x //= 5 |
&= | x = x & 5 | x &= 5 |
|= | x = x | 5 | x |= 5 |
^= | x = x ^ 5 | x ^= 5 |
>>= | x = x >> 5 | x >>= 5 |
<<= | x = x << 5 | x <<= 5 |
Let’s understand how these operators work in python:
a = 22 print("Value assigned to a",a) a += 5 print("Value of a after addition",a) a -= 5 print("Value of a after subtraction",a) a *= 5 print("Value of a after multiplication",a) a /= 10 print("Value of a after division",a) a %= 7 print("Value of a after modulus",a) a //= 2 print("Value of a after floor division",a) a **=5 print("Value of a after exponentiation ",a) a = int(a) a &= 5 print("Value of a after Bitwise AND",a) a |= 1 print("Value of a after Bitwise OR",a) a ^= 0 print("Value of a after Bitwise XOR",a) a *= 10 a >>= 2 print("Value of a after Bitwise right-shift",a) a <<= 2 print("Value of a after Bitwise left-shift",a)
Output Value assigned to a 22 Value of a after addition 27 Value of a after subtraction 22 Value of a after multiplication 110 Value of a after division 11.0 Value of a after modulus 4.0 Value of a after floor division 2.0 Value of a after exponentiation 32.0 Value of a after Bitwise AND 0 Value of a after Bitwise OR 1 Value of a after Bitwise XOR 1 Value of a after Bitwise right-shift 2 Value of a after Bitwise left-shift 8
7. Identity Operators (is or is not)
Identity operators are used for checking if two values reside in the same memory or not. In python we have two identity operators : is
and is not
is
returns true if values are identicalis not
returns true if values are not identical
Let’s understand how these operators work in python:
print(3 is 3) print((1, 2, 3) is (1, 2, 3)) # tuples are immutable print({1, 2} is {1, 2}) # sets are mutable print("Geeks" is not "geeks") print([1, 2, 3] is not [1, 2, 3]) # list is mutable
Output True True False True True
8. Membership operators (in or not in)
Membership operators are used for checking if the value is present in the sequence or not. In python we have two membership operator : in
and not in
in
return true if the value is there in the sequencenot in
return true if the value is not found in the sequence.
Let’s understand how these operators work in python:
print("eeks" in "geeks") print(5 not in [1, 2, 3]) print((1, 2) in (1, 2, 3)) print(2 not in {1, 2})
Output True True False False
In the above example (1,2) in (1,2,3)
returned false because the compiler is considering (1,2) whole as a tuple, not individual elements.
9. Precedence and Associativity of Operators
A number of logical and relationship expression can be linked together with the help of logical expression as shown below:
(x<y) OR (x>20) AND NOT(z) AND ((x<y) AND (z>5))
For a complex expression like this, it becomes difficult to make out as to in what order the evaluation of the subexpression will take place.
In python, the order of evaluation of an expression is carried out according to the operator precedence.
If the operator is of the same priority then to resolve this issue we check their Associativity.
Operators | Associativity | Priority |
---|---|---|
( ) | left-to-right | Highest |
** | right-to-left | | |
* / % | left-to-right | | |
+ – | left-to-right | | |
<< >> | left-to-right | | |
< <= > >= | left-to-right | | |
== != | left-to-right | Lowest |
10. Conclusion
In this aritcle we discussed about:
- Arithmetic operators
- Relational operators or Comparison operator
- Logical operators
- Bitwise operators
- Assignment operators
- Identity operators
- Membership operators
- Precedence and Associativity of Operators
Helpful Links
Please follow the Python tutorial series or the menu in the sidebar for the complete tutorial series.
Also for examples in Python and practice please refer to Python Examples.
Complete code samples are present on Github project.
Recommended Books
An investment in knowledge always pays the best interest. I hope you like the tutorial. Do come back for more because learning paves way for a better understanding
Do not forget to share and Subscribe.
Happy coding!! ?
Hi
I think that there is an error in the section 2.5. Modulus (%)
Should the anwser be 0 not 12.
Thanks for pointing it out Mathew. It is fixed now 🙂
also the 3%75 =0
because 3×25=75 and the remaider =0
No, as m%n if m<n the division is 0 with rest m
[…] use arithmetic operators for numerous operations. Among such arithmetic operators, there exists an addition […]
[…] Operators in Python […]
[…] Operators in Python […]
[…] Operators in Python […]
[…] Operators in Python […]
[…] Operators in Python […]
[…] Operators in Python […]
[…] Operators in Python […]