Python Operators

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

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

Arithmatic Operators

Mathematical operations on numberic values can be performed by Arithmatic Operators.

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

Operator Precedance

Control flow takes any expression left to right by default. However, their are predefined priority sequence for Python Operators, known as Operator Precedance. 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 assign a variable refernece for a value. The working of assignment is from right-hand-side to 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 check the containment of an item in a collection. There are two membership operators for contains check: in and not in.
Example:

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

not in gives us False whereever in gives True and vice-versa.
Example:

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