Python Operators

Operators are an essential part of any programming language. If you learn operators, you can use the programming language for your everyday tasks. In this post, you learn python operators so that you can start using it immediately.

Operators are special symbols to perform operations on variables and values. The values and variables that operators act on are called operands.

Python classifies operators in the following groups:

  1. Arithmetic Operators
  2. Assignment Operators
  3. Comparison Operators
  4. Logical Operators
  5. Identity Operators
  6. Membership Operators
  7. Bitwise Operators

Arithmetic Operators

Arithmetic operators are used to performing mathematical operations.

OperatorMeaningUsage
+Additionx + y
Subtractionx – y
*Multiplicationx * y
/Divisionx / y
//Floor Divisionx // y
%Modulus: Remainder of divisionx % y
**Exponentiation: left operand raised to the power of rightx ** 2

Examples

a = 8
b = 3

print('a + b = ', a + b)  			#  a + b = 11
print('a - b = ',  a - b)			#  a - b = 5
print('a * b = ', a * b)			#  a * b = 24
print('a / b = ',  a  / b) 			#  a / b = 2.6666666666666665
print('a % b = ', a % b)			#  a % b = 2
print('a // b = ', a // b)			# a // b = 2
print('a ** b = ', a ** b)			# a ** b = 512

Assignment Operators

Assignment operators are used to assigning values to variables.

x = y

The value of the y variable is assigned to the x variable.

There are also compound operators. Applying the first operator for the left and right operand, then assign the result to the left variable.

x += y          	#	x = x + y
x *= y		        #	x = x * y
OperatorMeaningUsageSame As
=Assign the right side of the expression to the left
operand
x = yx = y
+= Add the right side of the expression to the left and
assign to the left
x += yx = x + y
-=Subtract the ride side of the expression from the
left and assign to the left
x -= yx = x – y
*=Multiply the ride side of the expression with the
left side and assign to the left
x *= yx = x * y
/=Divide the right side of the expression to the
left side and assign to the left
x /= yx = x / y

Examples

a = 7
b = 2

c = a
print ('c = ', c)		# c = 7

a += b
print('a = ', a)		# a = 9

b *= 3
print('b = ', b)		# b = 6

Comparison Operators

Comparison operators are used to compare two operands; hence the name. Comparison operation returns a boolean value: True or False.

OperatorMeaningUsage
==Equalx == y
!= Not Equalx != y
>Greater Thanx > y
<Less Thanx < y
>= Greater Thanx >= y
<= Less Thanx <= y

Examples

a = 4
b = 4
print('a == b', a == b) 			# outputs True
print('a != b', a != b)				# outputs False

Logical Operators

Logical operators are used to combine boolean values.

OperatorMeaningUsage
andreturns true if both the operands are truex and y
orreturns true if one or both of the operands are truex or y
notreverses the operandnot x

Examples

x = True
y = False

print('x and y = ', x and y)			# x and y =  False
print('x or y = ', x or y)			# x or y = True
print('not x = ', not x)			# not x = False

Identity Operators

Identity operators used to check if two value is at the same memory location.

They do not check equality, as in comparison operator (==). It checks if the two operands (object, variable, constant) are identical.

OperatorMeaningUsage
ischecks if the two operands are identicalx is y
is notchecks if the two operands are not identicalx is not y

In Python, everything is an object. Numbers, lists, strings, all of them are objects. Some objects are mutable, meaning you can change their content without changing their identity: list, dict, set, byte array are mutable objects.

Integers, floats, strings, and tuples are immutable objects that can not be changed.

Immutable objects which have the same value are identical.

Mutable objects which refer to the same object are identical.

Examples

x1 = 'abc'

y1 = 'abc'

print('x1 is y1 =', x1 is y1)    	# it is not true, because string objects are immutable

print('x1 is not y1 =', x1 is not y1)

x2 = [1,2,3]

y2 = [1,2,3]

print('x2 is y2 =', x2 is y2)           # it is false, because list objects are mutable

x3  = x2

print('x2 is x3 =', x2 is x3)	        # it is true, refers to the same memory location

Membership Operators

Membership operators are used to check whether a value or variable is found in a sequence. By sequence, we mean string, list, tuple, set and dictionary.

OperatorMeaningUsage
inCheck if the value is found in the sequencex in y
not inCheck if the value is not found in the sequencex not in y

Examples

x = 3
y = [1, 2, 3]

print('x in y = ', x in y)		# x in y = True
print('4 in y = ', 4 in y)		# 4 in y = False

Bitwise Operators

Bitwise operators are used to perform on binary numbers. It operates bit by bit.

OperatorMeaningUsage
&Bitwise Andx & y
|Bitwise Orx | y
~Bitwise Not~x
^XORx ^ y
>>Bitwise Right shiftx >> 2
<<Bitwise Left shiftx << 2

Examples

x = 4			                #  x = 0000 0100 (binary)
y = 2			                #  y = 0000 0010 (binary)

print('x & y =', x & y)			# x & y = 0 

print('x | y =', x | y)			# x | y = 6 

print('~x =', ~x)			# ~x = -5 

print('x ^ y =', x ^ y)			# x ^ y = 6

print('x >> 2 =', x >> 2)		# x >> 2 = 1

print('x << 2 =', x << 2)		# x << 2 = 16

Operator Precedence

In a more complex statement, we can use multiple operators:

x = 4 + 3*2

Is the result 14 or 10? Python interpreter determines according to the precedence rules.

Presedence Rules

Operator (Decreasing Order)Usage
**Exponent
~x, +x, -x Bitwise not, Unary plus, Unary minus
*, /, % Multiply, Divide, Modulo
+, – Addition, subtraction
<<, >>Shifts left/right
&Bitwise AND
^Bitwise XOR
|Bitwise OR
in, not in, is, is not, <, <=, >, >=, !=, ==Membership, Identity, Comparison
not xBoolean NOT
andBoolean AND
orBoolean OR

However, if you find it confusing, you can always use parentheses, which makes the precedence explicit.

x = 4 + (3*2)	# result is 10

FAQ

What is the difference between ‘/’ and ‘//’ when used for division?

In python, the division operator returns a float number, no matter what the operands are. Operands could be integer or float. Either way, the result would be a float number.

Even the operands are fully divisible without remainder the result would be float:

x = 6
y = 3
print('x / y =', 6 / 3)		# x / y = 2.0

For our sample, the result is a float number (2.0). Therefore division operator / is also called floating point division.

Python // division operator, on the other hand, is a floor division. By floor division we mean, the result is round down to the nearest integer:

x = 8
y = 3

print('x // y =', x // y)	# x // y = 2

Does Python have a ternary conditional operator?

If you have used other programming languages like C, C#, or Java, there is an expression which is called a ternary operator.

In C# using symbols question mark (?) and colon (:) we are conditionally evaluating an expression.

For example (C# statement):

x = (y > 2 ? 3 : 5);  

If y is greater than 2 set x variable the number 3, otherwise set x the number 5.

You can make the same expression in python as below:

x = 0
y = 4

x = 3 if y > 2 else 5

print('x =', x)		# x = 3

Conclusion

Operators are the core part of any programming language structure. If you know another language, likewise python provides all operators for your programming tasks.

Leave a Comment