Python Operators

There are five groups of operators in the Python programming language: arithmetic, comparison, assignment, logical, identity, membership, and bitwise.

  • Arithmetic operators – are used to perform basic mathematical operations
  • Comparison operators – are used to compare values, they return a True/False based on the statement
  • Assignment operators – are used to perform some operation and assign a value to a variable
  • Logical operators – are used to combine conditional statements
  • Identity operators – are used to determine if objects are the same
  • Membership operators – are used to determine if a value is found in a sequence
  • Bitwise operators – are used to perform operations at the bit level

Combining Operators

You can combine various operators together:

>>>  x = 3
>>> (x < 5 + 1) and (x > 1)
True

Arithmetic Operators

OperatorDescriptionExample
+Addition8 + 3 = 11
Subtraction8 – 3 = 5
*Multiplication8 * 3 = 24
/Division8 / 3 = 2.66…
//Floor division – round down division16//3 = 5
%Modulo operation – remainder from division16%3 = 1
**Power operation2**3 = 8

Order of operation

In Python, just like in Math order of arithmetic operations is governed by PEMDAS – Parentheses, Exponent, Multiplication, Division, Addition, Subtraction.

>>> 3 + 2 * 8
19
>>> (3 + 2) * 8
40

Comparison Operators

OperatorDescriptionExample
==Equala == b
!=Not equala != b
>Greater thana > b
<Less thana < b
>=Greater than or equala >= b
<=Less than or equala <= b

Assignment Operators

OperatorDescriptionExample
=Assignmentx = 5
+=Addition assignmentx += 5
-=Subtraction assignmentx -= 5
*=Multiplication assignmentx *= 5
/=Division assignmentx /= 5
%=Modulus assignmentx %= 5
//=Floor division assignmentx //= 5
**=Power assignmentx **= 5
&=Bitwise AND assignmentx &= 5
|=Bitwise OR assignmentx != 5
^=Bitwise XOR assignmentx ^= 5
>>=Bitwise shift right assignmentx >>= 5
<<=Bitwise shift left assignmentx <<= 5

Logical Operators

OperatorDescriptionExample
andAnd logical operationx > 3 and x < 8
orOr logical operation x < 3 or x > 8
notNot logical operation not x

Identity Operators

OperatorDescriptionExample
isIs the same objectx is y
is notIs not the same object x is not y

Membership Operators

OperatorDescriptionExample
inIn a sequencex in [1, 2, 3]
not inNot in a sequence x not in [1, 2, 3]

Bitwise Operators

OperatorDescriptionExample
&Bitwise ANDx & 5
|Bitwise ORx | 5
^Bitwise XORx ^ 5
<<Bitwise shift leftx << 5
>>Bitwise shift rightx >> 5