Python Operators


Python Introduction By CodeHind Image

Operator in Python

Operators are the Symbols which is used for mathematical or Logical operation

Operators are the constructs, which can manipulate the value of operands

Consider the expression 2 + 3 = 5. Here, 2 and 3 are called operands and + is called the operator.



There are following types of Operator

  • Arithmetic operators
  • Assignment operators
  • Comparison operators
  • Logical operators
  • Identity operators
  • Membership operators
  • Bitwise operators


Arithmetic Operatos

Arithmetic operators are used with numeric values to perform common mathematical operations:


Operator Name Example
+ Addition a + b
- Subtraction a - b
* Multiplication a * b
/ Division a / b
% Modulus a - b
** Exponentiation a ** b
// Floor Division a // b


Assignment Operators

Assignment operators are used to assign values to variables:



Operator Example Same As
= a=5 a=5
+= a += 3 a = a + 3
-= a -= 3 a = a - 3
*= a *= 3 a = a * 3
/= a /= 3 a = a / 3
%= a %= 3 a = x % 3
//= a //= 3 a = a // 3
**= a **= 3 a = a ** 3
&= a &= 3 a = a & 3
|= a |= 3 a = a | 3
^= a ^= 3 a = a ^ 3
>>= a >>= 3 a = a >> 3
<<= a <<= 3 a = a << 3


Comparision Operatos

Comparison operators are used to compare two values:


Operator Name Example
== Equal a == b
!= Not Equal a != b
> Greater than a > b
< Less Than a < b
>= Greater Than or Equal To a >= b
<= Less Than or Equal To a <= b


Logical Operators

Logical operators are used to combine conditional statements:


Operator Description Example
and Returns True if both statements are true a < 5 and a < 10
or Returns True if one of the statements is true a < 5 or a < 4
not Reverse the result, returns False if the result is true not(a < 5 and a < 10)


Identity Operators

Identity operators are used to compare the objects, not if they are equal, but if they are actually the same object, with the same memory location:


Operator Description Example
is Returns True if both variables are the same object a is b
is not Returns True if both variables are not the same object a is not b


Membership Operators

Membership operators are used to test if a sequence is presented in an object:


Operator Description Example
in Returns True if a sequence with the specified value is present in the object a in b
not in Returns True if a sequence with the specified value is not present in the object a not in b


Bitwise Operators

Bitwise operators are used to compare (binary) numbers:


Operator Name Description
& AND Sets each bit to 1 if both bits are 1
| OR Sets each bit to 1 if one of two bits is 1
^ XOR Sets each bit to 1 if only one of two bits is 1
~ NOT Inverts all the bits
<< Zero fill left shift Shift left by pushing zeros in from the right and let the leftmost bits fall off
>> Signed right shift Shift right by pushing copies of the leftmost bit in from the left, and let the rightmost bits fall off