DEV Community

Eddie Svirsky
Eddie Svirsky

Posted on • Originally published at queworx.com

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

 

Arithmetic Operators

>>> 8 + 3
11
>>> 8 - 3
5
>>> 8 * 3
24
>>> 8 /3
2.6666666666666665
>>> 16//3
5
>>> 16%3
1
>>> 2**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

>>> a = 3
>>> b = 8
>>> a == b
False
>>> a != b
True
>>> a > b 
False
>>> a < b
True
>>> a >= b
False
>>> a <= b
True

 

Assignment Operators

 

Logical Operators

>>> 5 > 3 and 2 > 1
True
>>> 5 > 3 or 2 > 5
True
>>> not(5 > 3) 
False

 

Identity Operators

>>> x = [1, 2]
>>> y = [1, 2]
>>> x is y
False
>>> x is not y
True

 

Membership Operators

>>> 5 in [3, 5, 8]
True
>>> 5 not in [3, 5, 8]
False

 

Bitwise Operators

>>> 9 & 3
1
>>> 9 | 3
11
>>> 9 ^ 3 
10
>>> 9 << 2
36
>>> 9 >> 2
2

 

Combining Operators

You can combine the various operators above in various ways, such as:

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

Top comments (0)