Your ultimate guide

Operators in Python

Operators:
The operator is a symbol that performs certain operations.

Python provides the following set of operators.
1.  Arithmetic Operators
2.  Comparison Operators or Relational Operators
3.  Assignment Operators
4.  Logical Operators
5.  Bitwise Operators
6.  Membership
7.  Identity operators
8.  Precedence
 
Arithmetic Operators:
Arithmetic operators are used to perform mathematical operations. They are,
    +    » Addition
    -    » Subtraction
    *    » Multiplication
    /    » Division operator (always returns float value)
    //    » Floor Division operator (if the arguments are int type then the result is int type, if at least one argument is float type then the result is float type)
    %    » Modulo operator
    **    » Exponent operator or power operator
        Example:
            >>> a = 12
            >>> b = 3
            >>> print("a+b =", a+b)        #a+b = 15
            >>> print("a-b =", a-b)        #a-b = 9
            >>> print("a*b =", a*b)        #a*b = 36
            >>> print("a/b =", a/b)        #a/b = 4.0
            >>> print("a//b =", a//b)    #a//b = 4
            >>> print("a%b =", a%b)     #a%b = 0
            >>> print("a**b =", a**b)    #a**b = 1728 

        Note: 
            We can use +, * operators for the str type also.
            If we want to use the + operator for the str type, then compulsory both arguments should be str type only otherwise we will get the error.
        Example:
            >>> s = "Testing"+"Colleges"
            >>> print(s)        #TestingColleges
            >>> n = "Testing" +10
            TypeError: can only concatenate str (not "int") to str

                If we want to use the * operator for the str type, then compulsory one argument should be int type and the other argument should be str type.
        Example:
            >>> 2 * "testing"
            'testingtesting'
            >>> 1.5 * "testing"
            TypeError: can't multiply sequence by non-int of type 'float'
            >>> "testing" * "testing"
            TypeError: can't multiply sequence by non-int of type 'str'

Relational Operators:
Relational operators are used for comparing the value. It always returns a boolean(True/False) value only.
    >    » Greater than
    <    » Less than
    >=    » Greater than or Equal to
    <=    » Less than or Equal to
    ==    » Equal to
    !=    » Not Equal to

        Example:
            >>> a,b = 10,20
            >>> a>b
            False
            >>> a<b
            True
            >>> a>=b
            False
            >>> a<=b
            True
            >>> a == b
            False
            >>> a != b
            True
            >>> 10>20>30>40
            True
            >>> 10 == 20 == 30
            False

        Note:
            We can apply relational operators for str type also. It is always going to check alphabetical order.

Assignment Operators:
    We can use the assignment operator(=) to assign value to the variable. We can combine the assignment operator with another operator to form a compound assignment operator, they are +=, -=, *=, /=. //=, %=, **=, &=, |=, ^=, >>=, <<=
        Example:
            >>> a=10
            >>> a += 5        #(a = a + 5)
            >>> print(a)    #15
    
            >>> b = 20 
            >>> b -= 2
            >>> print(b)    #18

    Note: Increment (++) and decrement (--) operators are not worked in Python. 

Logical Operators:
There are 3 types of Logical operators in Python: and, or, not

    and » If both arguments are True then only the result is True, otherwise False (T + T = T).
        Example:
            >>> 10 < 20 and 20 >10
            True
            >>> 10 < 20 and 20 < 10
            False

    or » If at least one argument is True then the result is True (F + F = F).
        Example:
            >>> 10 < 20 or 20 < 10
            True
            >>> 10 > 20 or 20 < 10
            False

    not » it inverts to the result (T = F, F = T).
        Example:
            >>> not (10 > 20)
            True
            >>> not (10 < 20)
            False

Bitwise Operators:
#  Bitwise operators are used to perform bitwise calculations on integers.
#  The integers are first converted into the binary format and then operations are performed on each corresponding pair of bits, based on the given bitwise operator the result will return in decimal format.
#  These operators are applicable only for int and boolean types.
#  Bitwise Operator are &, |, ^, ~, <<, >>:
&   » Bitwise AND, if both bits are 1 then only the result is 1 otherwise the result is 0
|    » Bitwise OR, if at least one bit is 1 then the result is 1 otherwise result is 0
^   » Bitwise XOR, if bits are different then only the result is 1 otherwise result is 0
~   » Bitwise Complement operator, inverts individual bit (1 = 0, 0 = 1)
<<   » Bitwise Left shift
>>   » Bitwisr Right shit

    Example for Bitwise AND (&):
        >>> a = 10
        >>> b = 12
        >>> a & b    #8 (output)
    ------------------------------
    Background Process:
        ==> First integers are converted into binary format.
                    a = 10 ==> 1 0 1 0
                    b = 12 ==> 1 1 0 0
        ==> Then the operation is performed on each corresponding pair of bits, based on the given bitwise operator. 
        Here given the bitwise operator is "&" (a & b), AND operation performs if both bits are 1 then only the result is 1 otherwise the result is 0
        a & b : 
        1 0 1 0    = 10(a)
        1 1 0 0    = 12(b)
        ------
        1 0 0 0    = 8(a & b)    # 1 -> 1 = 1, 0 -> 1 = 0, 1 -> 0 = 0, 0 -> 0 = 0
        ------
        ==> Result will return in decimal format. So here, the result "1 0 0 0" is in the Binary format, if we convert this "1 0 0 0" to decimal then the final result is 8. (1 0 0 0 (binary) = 8 (decimal))
        ==> Like this based on the different bitwise operators we will perform certain actions.

    Bitwise Shift Operators:
        Bitwise Left shift operator (<<):
            The left operand's value is moved to its left by the number of bits specified in the right argument.
            Example:
                    >>> print(10 << 2)
                    output: 40
                
                    ==> Binary format of 10 is '1010' (00001010). if we specify zero's on the left side of a binary number its value will not change.
                    ==> (10 << 2) means, it shifts the left 2 empty cells(bits) into the right side. After shifting the empty cells we have to fill them with zero.

    
                    ==> 00101000 = 40     #(binary -> decimal)

        Bitwise Right shit operator (>>):
            The quantity of bits provided by the right parameter advances the position of the left operand.
                Example:
                    >>> print(10 >> 2)
                    Output: 2

    

                ==> 10 -> 00001010
                ==> 2   -> 00000010

Identity operators:
We can use identity operators for address comparison.
     Identify operators are 
        1) is
        2) is not   
    is    » returns true when 2 variables have the same memory location.
    is not    » return true when 2 variables have different memory locations.

    Note: id(): To get the address of object (Eg: >>> a=10    >>>id(a) )
        Example:
            >>> a = 10
            >>> a = b
            >>> print(a is b)    #True
            >>> c = 20
            >>> print(id(a), id(c))    #140735263138888 140735263139208
            >>> print(a is not c)    #True
            >>> print(a is not b)    #False

Membership operators:
    We can use Membership operators to check whether the given object present in the given collection. (It may be String, List, Set, Tuple or Dict)
    Membership operators are:
        1) in
        2) not in
    in    » returns true when value is present in the specified collection.
    not in    » returns true when value is not present in the specified collection.

        Example:
            >>> s = "testingcolleges blogger"
            >>> print('g' in s)    #True
            >>> print('a' in s)    #False
            >>> print('colleges' not in s)    #False

            >>> l = ["apple", "bat", "cat", "dog"]
            >>> print("bat" in l)    #True
            >>> print("fan" not in l)    #True

Operator Precedence:
    If multiple operators are present then which operator will be evaluated first is decided by operator precedence.

        Example:
            >>> print(2+5*2)    #12
            >>> print((2+5)*2)    #14

    The following list describes operator precedence in Python.
1.  ()    (Parentheses)
2.  **    (Exponent)
3.  +x, -x, ~x    (Unary plus, Unary minus, bitwise NOT)
4.  *, /, //, %    (Multiplication, Division, Floor division, Modulus)
5.  +, -    (Addition, Subtraction)
6.  <<, >>    (Bitwise shif operators)
7.  &    (Bitwise AND)
8.  ^    (Bitwise XOR)
9.  |    (Bitwise OR)
10.  ==, !=, >, >=, <, <=, is, is not, in, not in
11.  not    (Logical NOT)
12.  and    (Logical AND)
13.  or    (Logical OR)

No comments:

Post a Comment