Operators

Let us understand the below terms before we get into more details.

1. Operator

An operator is a symbol which has special meaning and performs an operation on single or multiple operands like addition, substraction etc. In the below example, + is the operator.

x = 1
y = 2
print (x+y)

2. Operand

An operand is what operators are applied on. In the above example x and y are the operands.

Python provides the below operator groups:

1. Arithmetic Operators

Python arithmetic operators are used to perform arithmetic operations on operands.

OperatorDescriptionExample
+Used to perform Addition8+2 = 10
-Used to perform Subtraction12-2 = 10
*Used to perform Multiplication5*2 = 10
/Used to perform Division100/10 = 10
%Used to perform Remainder40%10 = 0
**Used to perform Exponentiation10 ** 2
//Used to perform Floor division9 // 4

2. Comparison Operators

Python comparison operators are used to compare two operands.

OperatorDescriptionUsage
==Is equal tox == y
!=Not equal to!=x
>Greater thanx > y
>=Greater than or equal tox >= y
<Less thanx < y
<=Less than or equal tox <= y

3. Bitwise Operators

Python bitwise operators are used to perform bitwise operations on operands.

OperatorDescriptionUsage
&Bitwise AND(x > y) & (y > z)
|Bitwise OR(x > y) | (y > z)
^Bitwise XOR(x > y) ^ (y > z)
~Bitwise NOT(~x)
<<Bitwise Left Shiftx << y
>>Bitwise Right Shiftx >> y

4. Logical Operators

Below are the logical operators present in Python.

OperatorDescriptionUsage
&&Logical AND(x > y) && (y > z)
||Logical OR(x > y) || (y > z)
!Logical NOT(!x)

5. Assignment Operators

Below are the assignment operators present in Python.

OperatorDescriptionUsage
=Assignx = 10;
+=Add and assignx=10; x+=30; #x becomes 40
-=Subtract and assignx=40; x-=10; #x becomes 30
*=Multiply and assignx=10; x*=40; #x becomes 400
/=Divide and assignx=100; x /= 10; #x becomes 10
%=Modulus and assignx=100; x%=10; #x becomes 0
**=exponential calculation and assignx **= y is equivalent to x = x**y
//=floor division and assignx //= y is equivalent = x= x // y

6. Membership Operators

Membership operators are used to test if a sequence is present in a given object.

OperatorDescriptionUsage
inReturns True if a sequence is present in the objectx in y
not inReturns True if a sequence is not present in the objectx not in y

7. Identity Operators

Identity operators are used to compare the objects whether they same objects with the same memory location.

OperatorDescriptionUsage
isReturns true if both variables are actually same objectsx is y
is notReturns true if both variables are not the same objectsx is not y

Summary

TypeOperators
Arithmetic Operators+ - * / % ** //
Comparision Operators== != > >= < <=
Bitwise Operators& ^ | ^ ~ << >>
Logical Operators&& || !
Assignment Operators= += -= *= /= %= **= //=
Membership Operatorsin, not in
Identity Operatorsis, is not