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.

SymbolNameExample
+addition2.0 + 8.2
return: 10.2
subtraction2.0 – 8.2
return: -6.2
*multiplication2.0 * 8.2
return: 16.4
/division60 / 5
return: 12.0
%Modulus73 % 5
return: 3
**Exponentiation3**2
return: 9
//floor division61 // 5
return: 12
Arithmetic Operators

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.

SymbolNameExample
==equality6 == 5
return: False
<less than6 < 5
return: False
<=less than or equal to6 <= 5
return: False
>greater than6 > 5
return: True
>=greater than or equal to6 >= 5
return: True
!=Not equal to6 != 5
return: True
Relational or comparison operator

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.

SymbolNameExample
andLogical ANDTrue and False
return: False
orLogical ORTrue or False
return: True
notLogical NOTnot True
return: False
Logical Operators

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-

ExpressionOutput
True and FalseFalse
False and TrueFalse
True and TrueTrue
False and FalseFalse
Logical AND

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

ExpressionOutput
True or FalseTrue
False or TrueTrue
True or TrueTrue
False or FalseFalse
Logical OR

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

ExpressionOutput
not TrueFalse
not FalseTrue
Logical NOT

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

SymbolNameExamples
&Bitwise ANDx & y
|Bitwise ORx | y
^Bitwise XORx ^ y
~Bitwise NOT~ x
>>Bitwise right shiftx >>
<<Bitwise left shiftx <<
Bitwise Operators

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

ExpressionOutput
1 & 00
0 & 10
1 & 11
0 & 00
Bitwise AND

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

ExpressionOutput
1 | 01
0 | 11
1 | 11
0 | 00
Bitwise OR

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

ExpressionOutput
1 ^ 01
0 ^ 11
1 ^ 10
0 ^ 00
Bitwise XOR

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

ExpressionOutput
~ 01
~ 10
Bitwise NOT

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.

SymbolSame asExample
=x = 5x = 5
+=x = x + 5x += 5
-=x = x – 5x -= 5
*=x = x * 5x *= 5
/=x = x / 5x /= 5
%=x = x % 5x %= 5
**=x = x ** 5x **= 5
//=x = x // 5x //= 5
&=x = x & 5x &= 5
|=x = x | 5x |= 5
^=x = x ^ 5x ^= 5
>>=x = x >> 5x >>= 5
<<=x = x << 5x <<= 5
Python Assignment Operators

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 identical
  • is 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 sequence
  • not 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.

OperatorsAssociativityPriority
( )left-to-rightHighest
**right-to-left|
* / %left-to-right|
+ –left-to-right|
<< >>left-to-right|
< <= > >=left-to-right|
== !=left-to-rightLowest
Operator Precedence

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.

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!! 😊

Recommended -

Subscribe
Notify of
guest
6 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Mathew
Mathew
2 months ago

Hi
I think that there is an error in the section 2.5. Modulus (%)

>>> 60 % 5 
12

Should the anwser be 0 not 12.

Hitesh Garg
Admin
2 months ago
Reply to  Mathew

Thanks for pointing it out Mathew. It is fixed now πŸ™‚

trackback

[…] use arithmetic operators for numerous operations. Among such arithmetic operators, there exists an addition […]

trackback

[…] Operators in Python […]

trackback

[…] Operators in Python […]

trackback

[…] Operators in Python […]

6
0
Would love your thoughts, please comment.x
()
x