Python Operators


Operators are the first tools for processing variables and values. Python Operators can be grouped under these types:

  • Arithmetic Operators
  • Assignment Operators
  • Membership Operators
  • Logical Operators
  • Relational Operators
  • Identity Operators
  • Bitwise Operators

Arithmatic Operators


Mathematical operations on numeric values can be performed by Arithmetic Operators.

+ - * / // % **
  • + (Addition)
  • - (Subtraction)
  • * (Multiplication)
  • / (Division)
  • // (Floor Division): Returns the division outcome without the decimal part.
  • % (Modulus): Returns the remainder from a division.
  • ** (Exponent)


Operator Precedence


Control flow takes any expression left to right by default. However, there are predefined priority sequences for Python Operators, known as Operator Precedence. Operator priority sequence from highest to lowest is below:

  • ()
  • **
  • * / // %
  • + -

Note: If you encounter two operators from the same priority tier they are simply processed in Left to Right order.


Example:

    >>> 2+2*3
    8
    >>> (2+2)*3
    12                            

Assignment Operators


Assignment Operators are used to assigning a variable reference for a value. The working of the assignment is from the right-hand side to the left-hand side.

L.H.S ← R.H.S


Example:

    >>> x = 1
    >>> x = y # NameError
    >>> y = x # Correct assignment
    >>> y
    1
                                

Membership Operators


Membership Operators are used to checking the containment of an item in a collection. There are two membership operators for contains check: in and not in.

Example:

item in the collection

    >>> 'h' in "Hello"
    False
    >>> 'h' in "hello
    True
    >>> 1 in [2, 40, 100]
    False
                                


not in gives us False wherever in gives True and vice-versa.

Example:

    >>> 1 not in [2, 40, 100]
    True
    >>> 'a' not in "aeiou"
    False