Home » Python Programming » Operators in Python

# Operators in Python

In this tutorial, I am going to discuss about various types of operators in python, their use and precedence in an expression.

## Operators in Python

In every programming language, we have a set of operators. Operators are specifically the special characters which can manipulate the value of operands.

Operands are the values or variables which are getting operated on by the operators.

## Types of Operators

Python language supports the following types of operators :

• Arithmetic Operators
• Comparison (Relational) operators
• Assignment Operators
• Bitwise Operators
• Logical Operators
• Membership Operators
• Identity Operators

Let’s learn about these operators one by one.

### Arithmetic Operators

These are the simple arithmetic operators which are used for number manipulations.

The following table shows use of arithmatic operators in python with example.

Operator Description Example
+ Addition 13 + 5 = 18
Subtract 14 – 2 = 12
* Multiplication 9 * 5 = 45
/ Division 25 / 5 = 5
% Remainder from Integer division (Modulo) 44 % 4 = 0
** Raise to power (Exponentiation) 2 ** 3 = 8, 2 raised to the power of 3
// Integer Division 16 // 2 = 8

Let’s see some examples of these operators :

a = 42
b = 10
c = 0

print("Variable a = {}, Variable b = {}".format(a, b) )

c  = a + b
print("Addition: a + b = ",c)

#Subtraction
c = a - b
print("Subtraction: a - b = ",c)

#Multiplication
c = a * b
print("Multiplication: a * b = ",c)

#Division
c = a / b
print("Division: a / b = ",c)

#Modulo
c = a % b
print("Modulo: a % b = ",c)

#Integer Division
c = a // b
print("Integer Division: a // b = ",c)

#Exponent
print("Exponent: 3 ** 4 = ",3 ** 4)

Variable a = 42, Variable b = 10
Addition: a + b =  52
Subtraction: a - b =  32
Multiplication: a * b =  420
Division: a / b =  4.2
Modulo: a % b =  2
Integer Division: a // b =  4
Exponent: 3 ** 4 =  81

### Comparison(Relational) Operators

These operators perform comparison among the operands on either side and decide the relation among them, hence they are also called relational operators.

The following table shows use of comparision operators in python with example.

Operator Description Example
== Is equal to (5 == 8) is false
!= Is not equal to (3 != 6) is true
> Is greater than (9 > 4) is true
< Is less than (5 < 2) is false
>= Is greater than or equal to (7 >= 1) is true
<= Is less than or equal to (5 <= 13) is false

Let’s see some examples:

a = 30
b = 48

print("Variable a = {}, Variable b = {}".format(a, b) )

c = a == b
print("a == b ? : ",c)

c = a != b
print("a != b ? : ",c)

c = a > b
print("Is a > b ? : ",c)

c = a < b
print("Is a < b ? : ",c)

c = a >= b
print("Is a >= b ? : ",c)

c = a <= b
print("Is a <= b ? : ",c)

Variable a = 30, Variable b = 48
a == b ? :  False
a != b ? :  True
Is a > b ? :  False
Is a < b ? :  True
Is a >= b ? :  False
Is a <= b ? :  True

Generally, these relational operators are used to complete flow of a program by using them in control statements. We are going to learn about them later.

### Assignment Operators

As the name suggests assignment operators are used for assignment purpose.

The following table shows the use of assignment operators in python with example.

Consider a, b and c as three numeric variables.

Operator Description Example
= Simple Assignment c = a + b assigns value of a + b to c
+= Assignment with addition c += a is equivalent to c = c + a
-= Assignment with subtraction c -= a is equivalent to c = c - a
*= Assignment with multiplication c *= a is equivalent to c = c * a
/= Assignment with division c /= a is equivalent to c = c / a
%= Assignment with Modulo c %= a is equivalent to c = c % a
**= Assignment with Exponentiation c **= a is equivalent to c = c ** a
//= Assignment with Integer division c //= a is equivalent to c = c // a

Let's see some examples :

a = 42
b = 10

print("Variable a = {}, Variable b = {}".format(a, b) )

a += b
print("Addition: a +=b or a + b = ",a)

# Subtraction
a -= b
print("Subtraction: a -= b or a - b = ",a)

# Multiplication
a *= b
print("Multiplication: a *= b or a * b = ",a)

# Division
a /= b
print("Division: a /= b or a / b = ",a)

# Modulo
a %= b
print("Modulo: a %= b or a % b = ",a)

#Integer Division
a = 14
b = 3
a //= b
print("Integer Division: {} //= {} is {} ".format(14, 3, a))

# Exponent
a = 2
b = 5
a **= b
print("Exponent: {} **= {} is {} ".format(2, 5, a))
Variable a = 42, Variable b = 10
Addition: a +=b or a + b =  52
Subtraction: a -= b or a - b =  42
Multiplication: a *= b or a * b =  420
Division: a /= b or a / b =  42.0
Modulo: a %= b or a % b =  2.0
Integer Division: 14 //= 3 is 4
Exponent: 2 **= 5 is 32 

### Python Bitwise Operator

Bitwise operators alter binary strings at bit level and performs bit-by-bit operation.

Consider two variables a = 6 an b = 13. In binary format they will be represented as follows.

a = 0000 0110
b = 0000 1101

If we wish to obtain binary representation of an integer python's built-in function bin() can be used as shown below :

a = 6
b = 13
print(a, ":", bin(a))
print(b, ":", bin(b))
6 : 0b110
13 : 0b1101

The following is a list of operators supported by python for bitwise operations:

Operator Description Example
& Bitwise AND (Binary AND) (a & b)
| Bitwise OR (Binary OR) (a | b)
^ Bitwise XOR (Binary XOR) (a ^ b)
~ BitWise Negation (Binary One's complement) ~a
<< Binary Left shift a << 2 (moves value of a by 2 bits to the left)
>> Binary Right shift a >> 2 (moves value of a by 2 bits to the right)

Let's see some examples:

a = 5
b = 12
print("a = ",a," : ",bin(a)," and b = ",b," : ",bin(b))

c = a & b
print("Binary AND : a & b = ",c," : ",bin(c))

c = a | b
print("Binary OR : a | b = ",c," : ",bin(c))

c = a ^ b
print("Binary XOR : a ^ b = ",c," : ",bin(c))

c = ~a
print("Binary NOT : ~a = ",c," : ",bin(c))

c = a << 3
print("Binary Left shift : a << 3 = ",c," : ",bin(c))

c = a >> 2
print("Binary Right shift : a >> 2 = ",c," : ",bin(c))
a =  5  :  0b101  and b =  12  :  0b1100
Binary AND : a & b =  4  :  0b100
Binary OR : a | b =  13  :  0b1101
Binary XOR : a ^ b =  9  :  0b1001
Binary NOT : ~a =  -6  :  -0b110
Binary Left shift : a << 3 =  40  :  0b101000
Binary Right shift : a >> 2 =  1  :  0b1

### Python Logical Operators

Following are the logical operators supported by python.

Operator Description Example
Logical AND If both operands are True then returns True (True and False) is False
Logical OR If any of the operand has value True then returns True (True or False) is True
Logical Not It performs negation on the operand Not(True) is False

These logical operators are generally used in flow of control in program structure i.e. they are used to decide the flow of the program.

Let's see some examples:

a = True
b = False

print("a = {}, and b = {}".format(a, b))
print("a and b = ", a and b)
print("a or b = ", a or b)
print("not a = ", not a)
a = True, and b = False
a and b =  False
a or b =  True
not a =  False

Truth table for these operations are as given :

Truth Table for AND Operator :

A B A and B
True True True
True False False
False True False
False False False

Truth Table for OR Operator :

A B A and B
True True True
True False True
False True True
False False False

Truth Table for NOT Operator :

A Not A
True False
False True

### Membership Operators

Python also offers some operators are called membership operators. These are used to test whether a value or variable is present in a sequence ( like strings, list, sets, dictionary, tuples).

There are two membership operators as shown:

Operator Description Example
in If value or variable is found in the sequence then it evaluates to True 2 in x
not in If value or variable is not found in the sequence then it evaluates to True 2 not in x

Let's see some examples:

str1 = "Learning Python"
dict1 = { 1:'one', 2:'two'}

print("Learn in str1 ? : ",'Learn' in str1)
print("python in str1 ? : ",'python' in str1)

print("1 in dict1 ? : ", 1 in dict1)
print("2 not in dict1 ? : ", 2 not in dict1)
print("one in dict1 ? : ", 'one' in dict1)

Learn in str1 ? :  True
python in str1 ? :  False
1 in dict1 ? :  True
2 not in dict1 ? :  False
one in dict1 ? :  False

in above code, 'Python' is in str1 but 'python is not in str1 (as python is case-sensitive language). Similarly, 1 is a key and 'one' is value in dictionary dict1 hence 'one' in dict1 returns false.

### Identity Operators

In python there are operators that compare memory locations of two objects. These are called identity operators.

Python has two identity operators as shown below :

Operator Description Example
is If both operands point to the same object then returns True a is b
is not If both operands point to different objects then returns True a is not b

Let's see some examples :

a = 20
b = 20
print("a is b ? : ", a is b )
c = 35
print("a is c ? : ", a is c )
print("b is not c ? : ",b is not c )
a is b ? :  True
a is c ? :  False
b is not c ? :  True

As observed above a and b point to the same memory location thus is operator evaluating to True. We can also verify this by using id( ) function provided by python. This function returns identity(unique integer) of an object.

For example :

print("a = ",a," : ",id(a)," and b = ",b," : ",id(b))
a =  20  :  140729107453344  and b =  20  :  140729107453344

As a and b have same value i.e. 20 they point to the same memory location and thus has same unique integer assigned to them.

## Operator Precedence in Python

In python, when we combine values, variables, operators or functions it forms an expression. Once the expression is executed,the python interpreter check the validity of that expression.

We have discussed about different types of expressions like arithmetic expressions, string expressions, relational expressions, logical expressions and compound expressions.

Now we will look into how an expression is evaluated in python.

For example: '4 + 7' is a valid python expression with values 4 and 7 and operator '+'.
But this is the simplest form of expression.

An expression might contain multiple values, variables and operators,to decide the evaluation order python gives operator precedence chart which shows which operator will be evaluated first and which last.

Python interpreter follows this precedence order and moves from left to right while evaluating an expression.

Given below is the precedence order of python operators from highest to the lowest precedence.

Operator Description
( ) Parentheses
** Exponentiation
~, +, - Bitwise not, Unary plus and Unary minus
*, /, %, // Multiply, Divide, Modulo, Integer Division
>>, << Bitwise Left-shift and Right-shift operators
& Bitwise 'AND'
^, | Bitwise exclusive 'OR' and regular 'OR'
<=, <, >, >= Comparison operators
==, != Equality operators
=, %=, +=, -=, /=, //=, *=, **= Assignment operators
is, is not Identity operators
in, not in Membership operators
not, or, and Logical operators

Examples :

a = 10
b = 2
c = 5
print("a = {}, b = {}, c = {}".format(a, b, c))

exp1 = a ** (b + c)
# parentheses have highest precedence
print("a ** (b + c) = ",exp1)

exp2 = a ** b + c
# ** has higher precedence than + hence a ** b is evaluated first
print("a ** b + c = ",exp2)
a = 10, b = 2, c = 5
a ** (b + c) =  10000000
a ** b + c =  105

As we can see in above examples, python interpreter follows the operator precedence table and moves from left to right while evaluating expressions with multiple operators.

## Conclusion

In this tutorial, we have discussed about operators and their types. We have seen each type of operators in detail with examples and also looked at operator precedence and expression evaluation in python.

If you have any questions please comment below and also share your views and suggestions in the comment box.