Skip to content

Operators

Dictionary

Operators : used to perform arithmetic and logical operations on data.

Operators enable us to manipulate and interpret data to produce useful outputs.

Python’s operators follow in-fix notation. In-fix operators appear between two operands.

Python divides the operators into the following groups:

  • Arithmetic operators
  • Assignment operators
  • Comparison operators
  • Logical operators
  • Bitwise operators

Arithmetic Operators

Arithmetic operators are used to perform mathematical operations like addition, subtraction, multiplication and division.

Below, we can find the basic arithmetic operators in order of precedence

Operator Purpose
() Parentheses
** Exponent
%, *, /, // Modulo, Multiplication,
Division, Floor Division
+, - Addition, Subtraction

Addition

Adds two objects.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
print(2 + 8)

float1 = 1.65
float2 = 5.40
print(float1 + float2)

num = 20
flt = 10.8
print(num + flt)

str_a = 'hello'
str_b = ' world'
print(str_a + str_b)
Result
1
2
3
4
10
7.050000000000001
30.8
hello world

Info

Using the + operator between two strings/characters is a concatenation operation. You cannot add a string type with an integer type.

Subtraction

Gives the subtraction result of two numbers.

1
2
3
4
5
6
7
8
9
print(2 - 50)

float1 = -2.88
float2 = 9.99
print(float1 - float2)

num = 50
flt = 20.8
print(num - flt)
Result
1
2
3
-48
-12.870000000000001
29.2

Multiplication

For numeric types, it outputs the multiplication of two numbers. For sequence types, the sequence extends over by n times (where n is numeric type).

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
print(10 * 10)          

float1 = 2.5
float2 = 8.5
print(float1 * float2)  

print(8.2 * 3)          

str_a = 'hello'
print(str_a * 3)        
Result
1
2
3
4
100
21.25
24.599999999999998
hellohellohello

Division

Divide x by y.

1
2
3
4
5
6
7
print(20 / 10) 

float1 = 5.5            
float2 = 4.5
print(float1 / float2) 

print(99.4 / 2) 
Result
1
2
3
2.0
1.2222222222222223
49.7

A result of division operation always results in a decimal number.

Bug

1.2222222222222223 can be considered as a bug in Python, but it is not. This has little to do with Python, and much more to do with how the underlying hardware handles floating-point numbers.

Check floating point section in the documentation for more such examples.

Floor Division

The result is floored to the nearest smaller integer.

1
2
3
4
5
6
7
print(111 // 10)

float1 = 5.5
float2 = 4.5
print(5.5 // 4.5)

print(22.5 // 2)
Result
1
2
3
11
1.0
11.0

Tip

Unlike normal division, floor division between two integers results in an integer.

Modulo

Returns the remainder of the division.

1
2
3
4
5
6
7
8
print(44 % 3) 

twenty_eight = 28
print(twenty_eight % 10) 

print(-99 % 10)     # The remainder is positive if the right-hand operand is positive
print(99 % -10)     # The remainder is negative if the right-hand operand is negative
print(32.4 % 1.5)   # The remainder can be a float
Result
1
2
3
4
5
2
8
1
-1
0.8999999999999986

Exponent

Returns x to the power of y.

1
2
3
4
print(2**8)         # 2 to the power 8  

flt_pt = -4.5 
print(flt_pt**4)    # -4.5 to the power 4
Result
1
2
256
410.0625

Precedence

Whenever operators have equal precedence, the expression is computed from the left side.

1
2
3
4
5
6
# Different precedence
print(10 - 3 * 2)  # Multiplication computed first, followed by subtraction

# Same precedence
print(3 * 20 / 5)  # Multiplication computed first, followed by division
print(3 / 20 * 5)  # Division computed first, followed by multiplication
Result
1
2
3
4
12.0
0.75

Parentheses

An expression that is enclosed inside parentheses will be computed first, regardless of operator precedence.

1
2
print((22 - 3) * 2)         # Subtraction occurs first
print((99 + 2) / (20 % 3)) 
Result
1
2
38
50.5

Assignment Operators

This is a category of operators which is used to assign values to a variable.

Below, we can find the basic assignment operators

Operator Purpose
= Assign
+= Add and Assign
-= Subtract and Assign
*= Multiply and Assign
/= Divide and Assign
//= Floor Divide and Assign
**= Raise Power and Assign
%= Modulo and Assign
|= Bitwise OR and Assign
&= Bitwise AND and Assign
^= Bitwise XOR and Assign
>>= Bitwise Right-Shift and Assign
<<= Bitwise Left-Shift and Assign

Assigning Values

Let's go through few examples

1
2
3
4
5
6
7
8
age = 51
print(age)

age = 53        # Remember variables are mutable
print(age)

age = age + 5   # 5 is added to the variable and new value is assigned
print(age)
Result
1
2
3
51
53
58

Copying the value of a variable to another variable.

1
2
3
4
5
6
7
first = 100
second = first      # value of `first` is assigned to variable `second`

first = 10          # value of `first` has been changed

print(first)        
print(second)
Result
1
2
10
100

Other Operators

Let's perform operations using above-defined operators. We'll play a game. Let's say I ask you to think of a number, I'll tell you the steps/operations you need to perform and whatever your number is, the answer will always be 10.

Let's assume you thought of number 55,

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
original_num = 55       # your guessed number
num = original_num      # assigning value to different variable 
print(num)

num += 5        # equivalent to `num = num + 5`
print(num)

num *= 3        # equivalent to `num = num * 3`
print(num)

num -= 15       # equivalent to `num = num - 15`
print(num)      

num //= original_num       # equivalent to `num = num // original_num`
print(num)

num += 7        # equivalent to `num = num + 7`
print(num)
Result
1
2
3
4
5
6
55
60
180
165
3
10

Voila, the answer is 10. You can try modulo and exponent operators. I'll explain bitwise operations in the Bitwise Operators section below.

Comparision Operators

Comparison operators can be used to compare values in mathematical terms. The result is either True or False according based on the condition.

Below, we can find the basic assignment operators,

Operator Purpose
> Greater Than
< Less Than
>= Greater Than or Equal to
<= Less Than or Equal to
== Equal to
!= Not Equal to
is Equal to (Identity)
is not Not Equal to (Identity)

Info

is and is not are the identity operators both are used to check if two values are located on the same part of the memory.

Two variables that are equal do not indicate that they are identical.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
num1 = 55
num2 = 10
num3 = 10

print(num2 > num1)  # 10 is less than 55
print(num1 > num2)  # 55 is greater than 10 

print(num2 == num3)  # Both have the same value
print(num3 != num1)  # Both have different values

print(3 + 10 == 5 + 5)  # Both are not equal
print(3 <= 2)  # 3 is not less than or equal to 2
Result
1
2
3
4
5
6
False
True
True
True
False
False

Note

We will understand is and is not utility later on.

Logical Operators

Logical operators are used to manipulate the logic of Boolean expressions.

Below, we can find the logical operators,

Operator Purpose
and True if both operands are True
or True if either of the operands is True
not True if an operand is False

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
# OR Expression
my_bool = True or False
print(my_bool)

# AND Expression
my_bool = True and False
print(my_bool) 

# NOT expression
my_bool = False
print(not my_bool) 
Result
1
2
3
True
False
True

Info

In bit terms, the value of True corresponds to 1 and False corresponds to 0.

1
2
3
4
num = 10

print(num*True)  
print(num*False) 
Result
1
2
10
0

Bitwise Operators

Bitwise operators are used to perform bitwise calculations on integer data type. The integers are first converted into binary and then operations are performed bit by bit. The result is returned in decimal format.

Tip

All data is made up of 0s and 1s known as bits.

Below, we can find the bitwise operators,

Operator Purpose
& Bitwise AND
| Bitwise OR
^ Bitwise XOR
~ Bitwise NOT
>> Shift bits right
<< Shift bits left

Bitwise AND Operator

Returns 1 if both the bits are 1 else 0.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
a = 10          # Binary format : 1010
b = 4           # Binary format : 0100

"""
    1010
       &
    0100
  = 0000
"""

print(a & b)
Result
1
0

Bitwise OR Operator

Returns 1 if either of the bit is 1 else 0.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
a = 10          # Binary format : 1010
b = 4           # Binary format : 0100

"""
    1010
       |
    0100
  = 1110
"""

print(a | b) 
Result
1
14

Bitwise XOR Operator

Returns 1 if one of the bits is 1 and the other is 0 else returns false.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
a = 10          # Binary format : 01010
b = 20          # Binary format : 10100

"""
    01010
        ^
    10100
  = 11110
"""

print(a ^ b)  
Result
1
30

Bitwise NOT Operator

Returns one’s complement of the number.

1
2
3
4
5
6
7
8
9
a = 10          # Binary format : 1010

"""
      ~1010
    = -(1010 + 1)
    = -(1011)
"""

print(~a) 
Result
1
-11

Bitwise Shift Operators

These operators are used to shift the bits of a number left side or right side. It has similar effects when we are multiplying or dividing the number by two.

Right-Shift Operator

Shifts the bits of the number to the right and fills 0 on voids left.

Tip

Similar effect as of dividing the number with some power of two.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
a = 20         # Binary format : 10100

"""
    = 0001 0100 >> 3
    = 0000 1010 (move one step to right)
    = 0000 0101 (move one more step right)
    = 0000 0010 (move one more step right)
    (Operation Complete)
"""

print(a >> 3)  
Result
1
2

Left-Shift Operator

Shifts the bits of the number to the left and fills 0 on voids left.

Tip

Similar effect as of multiplying the number with some power of two.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
a = 10         # Binary format : 01010

"""
    = 0000 1010 << 2
    = 0001 0100 (move one step to left)
    = 0010 1000 (move one more step left)
    (Operation Complete)
"""

print(a << 2) 
Result
1
40

Precedence and Associativity

Operator precedence and associativity determine the priorities of the operator.

Operator Purpose Associativity
() Parentheses left-to-right
** Exponent right-to-left
%, *, /, // Modulo, Mutiplication,
Division, Floor Division
left-to-right
+, - Addition, Subtraction left-to-right
>>, << Bitwise shift right
Bitwise shift left
left-to-right
<, <=
>, >=
Relational less than, less than or equal to
greater than, greater than or equal to
left-to-right
==, != Relational equal to and not equal to left-to-right

Let us understand what is right-to-left associativity means,

1
2
3
4
5
6
7
8
# right-left associativity

'''
2 ** 3 ** 2 is calculated as  
2 ** (3 ** 2) and not as (2 ** 3) ** 2 
'''

print(2 ** 3 ** 2)
Result
1
512

In the next section, we will start with Conditional Statements.

Back to top