Operators in Python 3

2409

In this article, we will learn about various Python operators divided into the following categories:

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

 

Arithmetic operators in Python

OperatorNameExample
+Additiona + b
-Subtractiona - b
*Multiplicationa * b
/Divisiona / b
%Modulusa % b

**Exponentiationa ** b
//Floor divisiona // b

Assignment operators in Python

OperatorExampleEquivalent to
=a = 5a = 5
+=a += 3a= a + 3
-=a -= 3a = a - 3
*=a *= 3a = a * 3
/=a /= 3a= a / 3
%=a %= 3a = a % 3
//=a //= 3a = a // 3
**=a **= 3a = a ** 3
&=a &= 3a = a & 3
|=a |= 3a = a | 3
^=a^= 3a= a ^ 3
>>=a >>= 3a = a >> 3
<<=a <<= 3a = a << 3

 

Comparison operators in Python

OperatorNameExample
==Equala == b
!=Not equala != b
>Greater thana > b
<Less thana < b
>=Greater than or equal toa >= b
<=Less than or equal toa <= b

 

Logical operators in Python

OperatorDescriptionExample
ANDReturns True if both statements are truea < 4 and a < 11
ORReturns True if one of the statements is truea < 7 or x < 3
NOTReverse the result, returns False if the result is truenot(a < 1 and a < 5)

 

Identity operators in Python

OperatorDescriptionExample
is Returns true if both variables are the same objecta is b
is notReturns true if both variables are not the same objecta is not b

 

Membership operators in Python

OperatorDescriptionExample
in Returns True if a sequence with the specified value is present in the objecta in b
not inReturns True if a sequence with the specified value is not present in the objecta not in b

 

Bitwise operators in Python

OperatorNameDescription
&ANDSets each bit to 1 if both bits are 1
|ORSets each bit to 1 if one of two bits is 1
^XORSets each bit to 1 if only one of two bits is 1
~NOTInverts all the bits
<<Zero fill left shiftShift left by pushing zeros in from the right and let the leftmost bits fall off
>>Signed right shiftShift right by pushing copies of the leftmost bit in from the left, and let the rightmost bits fall off