Python Operators
Python Operators

Python operators are a list of symbols or special characters that are used to perform specific operations on one or more operands (values or variables). Python provides several types of operators, including arithmetic operators, assignment operators, bitwise operators, comparison operators, identity operators, logical operators, and membership operators. In this article, we cover all of these operators and explain their purpose and also provide practical examples.

Python Arithmetic Operators

Arithmetic operators are used to perform mathematical calculations. Therefore, Python supports a list of arithmetic operators to perform a specific operation. Such arithmetic operators in Python include:

  • Addition (+): Adds two operands.

    Example:

    
    a = 20
    b = 40
    c = 10
    
    # USE ADDITIONAL OPERATOR TO COMBINE TWO OR MORE VALUES IN PYTHON
    print("a: ", a, "b: ", b, "c: ", c, "Result: a + b + c = ", a + b + c)
    
    # Output: a:  20 b:  40 c:  10 Result: a + b + c =  70
    
  • Subtraction (-): Subtracts the right operand from the left operand.

    Example:

    
    a = 20
    b = 40
    c = 10
    
    # USE SUBTRACTION OPERATOR TO SUBTRACT TWO OR MORE VALUES IN PYTHON
    print("a: ", a, "b: ", b, "c: ", c, "Result: b - a - c = ", b - a - c)
    
    # Output: a:  20 b:  40 c:  10 b - a - c =  10
    
  • Multiplication (*): Multiplies two operands.

    Example:

    
    a = 2
    b = 4
    c = 3
    
    # USE MULTIPLICATION OPERATOR TO MULTIPLY TWO OR MORE VALUES IN PYTHON
    print("a: ", a, "b: ", b, "c: ", c, "Result: b * a * c = ", b * a * c)
    
    # Output: a:  2 b:  4 c:  3 Result: b * a * c =  24
    
  • Division (/): Divides the left operand by the right operand (result is always a float).

    Example:

    
    a = 5
    b = 40
    c = 2
    
    # USE DIVISION OPERATOR TO DIVIDE TWO OR MORE VALUES IN PYTHON
    print("a: ", a, "b: ", b, "c: ", c, "Result: b / a / c = ", b / a / c)
    
    # Output: a:  5 b:  40 c:  2 Result: b / a / c =  4.0
    
  • Floor Division (//): Performs division and returns the floor value. When you perform the floor division using the // operator, the decimal part of the division result is truncated, and the quotient is rounded down to the nearest whole number. It’s important to note that the floor division operator always returns an integer value, regardless of the operands’ data types. If both operands are integers, the result will be an integer.
    However, if one or both operands are floating-point numbers, the result will still be an integer (But the output will be a float type with zero decimal point), but the division operation will be performed on the floating-point values before rounding down.

    Example:

    
    a = 5
    b = 40
    c = 2.2
    
    # USE FLOOR DIVISION OPERATOR TO DIVIDE TWO OR MORE VALUES IN PYTHON
    print("a: ", a, "b: ", b, "Result: b // a = ", b // a)
    
    # Output: a:  5 b:  40 Result: b // a =  8
    
    print("a: ", a, "c: ", c, "Result: a // c = ", a // c)
    # Output: a:  5 c:  2.2 Result: a // c =  2.0
    
  • Modulo (%): Returns the remainder of the division. The modulo operator is commonly used in various scenarios, such as checking divisibility or cycling through a range of values. We can also use it to check if a number is even or odd using the modulo operator.

    Example:

    
    a = 5
    b = 24
    
    # USE MODULUS OPERATOR TO RETURN THE REMINDER OF TWO VALUES AFTER BEING DIVIDED IN PYTHON
    print("a: ", a, "b: ", b, "Result: b % a = ", b % a)
    
    # Output: a:  5 b:  24 Result: b % a =  4
    
    # USE MODULUS OPERATOR TO CHECK IF THE NUMBER IS ODD OR EVEN IN PYTHON
    c = 7
    
    if c % 2 == 0:
        print("The Number is Even")
    else:
        print("The Number is Odd")
    
    # Output: The Number is Odd
    
  • Exponentiation (**): Raises the left operand to the power of the right operand. The exponentiation operator allows you to perform calculations involving exponential powers easily.

    Example:

    
    a = 2
    b = 5
    
    # USE THE EXPONENTIATION OPERATOR IN PYTHON
    print("a: ", a, "b: ", b, "Result: b ** a = ", b**a)
    
    # Output: a:  2 b:  5 Result: b ** a =  25
    

Python Assignment Operators

Assignment operators in Python are used to assign values to variables. Optionally, we can combine an arithmetic operation with the assignment operators or bitwise operator with assignment operators to perform a specific task.
The following shows some of the ways we can combine the assignment operators together with arithmetic operators:

  • Assignment (=): Assigns the value on the right to the variable on the left.

    Example: Assignment Operator (=)

    
    a = 2
    b = 5
    c = 20
    
    # USE THE ASSIGNMENT OPERATOR IN PYTHON
    print("a: ", a, "b: ", b, "c:", c)
    
    # Output: a:  2 b:  5 c: 20
    
  • Addition Assignment (+=): Adds the value on the right to the variable on the left and assigns the result to the left operand. The Addition Assignment operator is a shorthand way of performing addition and updating the value of the variable in a single step.

    Example: Addition Assignment Operator (+=)

    
    a = 5
    a += 5  # equivalent to a = a + 5
    b = 20
    b += a  # equivalent to b = b + a
    c = 2
    c += a + b  # equivalent to c = c + a + b
    
    # USE THE ASSIGNMENT OPERATOR IN PYTHON
    print("a: ", a, "b: ", b, "c:", c)
    
    # Output: a:  10 b:  30 c: 42
    
  • Subtraction Assignment (-=): The Subtraction Assignment operator (-=) in Python combines subtraction with assignment. It subtracts the value of the right operand from the value of the left operand and assigns the result back to the left operand.
    This allows you to write simple and concise code specifically when you want to perform subtraction and assign the result back to a variable.

    Example: Subtraction Assignment Operator (-=)

    
    a = 10
    a -= 5  # equivalent to a = a - 5
    b = 40
    b -= a  # equivalent to b = b - a
    
    # USE THE ASSIGNMENT OPERATOR IN PYTHON
    print("a: ", a, "b: ", b)
    
    # Output: a:  5 b:  35
    
  • Multiplication Assignment (*=): Multiplies the variable on the left by the value on the right and assigns the result to the left operand. This also is a shorthand way of performing multiplication and updating the value of the variable in a single step.

    Example: Multiplication Assignment Operator (*=)

    
    a = 10
    a *= 2  # equivalent to a = a * 2
    b = 3
    b *= a  # equivalent to b = b * a
    
    # USE THE ASSIGNMENT OPERATOR IN PYTHON
    print("a: ", a, "b: ", b)
    
    # Output: a:  20 b:  60
    
  • Division Assignment (/=): Divides the variable on the left by the value on the right and assigns the result to the left operand. This is a shorthand way of writing a simple and concise code especially when you need to perform multiplication and assign the result back to the left operand (variable).

    Example: Division Assignment Operator (/=)

    
    a = 6
    a /= 2  # equivalent to a = a / 2
    b = 3
    b /= a  # equivalent to b = b / a
    
    # USE THE ASSIGNMENT OPERATOR IN PYTHON
    print("a: ", a, "b: ", b)
    
    # Output: a:  3.0 b:  1.0
    
  • Modulo Assignment (%=): Calculates the modulo of the variable on the left and the value on the right, then assigns the result to the left operand. This is a shorthand way of performing such an operation as shown in the following example.

    Example: Modulo Assignment Operator (%=)

    
    a = 5
    a %= 2  # equivalent to a = a % 2
    b = 30
    b %= 4  # equivalent to b = b % 4
    
    # USE THE ASSIGNMENT OPERATOR IN PYTHON
    print("a: ", a, "b: ", b)
    
    # Output: a:  1 b:  2
    
  • Floor Division Assignment (//=): The Floor Division Assignment (//=) operator in Python combines the floor division operation and assignment. It divides the left operand by the right operand using floor division and assigns the result back to the left operand.
    In other words, the Floor Division Assignment operator is a shorthand way of performing floor division and updating the value of the variable in a single step.

    Example: Floor Division Assignment Operator (//=)

    
    a = 15
    a //= 3  # equivalent to a = a // 3
    b = 30
    b //= 4  # equivalent to b = b // 4
    
    # USE THE ASSIGNMENT OPERATOR IN PYTHON
    print("a: ", a, "b: ", b)
    
    # Output: a:  5 b:  7
    
  • Exponentiation Assignment (**=): The Exponentiation Assignment (**=) operator in Python combines exponentiation and assignment. It raises the left operand to the power of the right operand and assigns the result back to the left operand.
    We use such an operation as a shorthand way of performing exponentiation and updating the value of the variable in a single step.

    Example: Exponentiation Assignment Operator (**=)

    
    a = 5
    a **= 2  # equivalent to a = a ** 2
    b = 2
    b **= 2  # equivalent to b = b ** 2
    
    # USE THE ASSIGNMENT OPERATOR IN PYTHON
    print("a: ", a, "b: ", b)
    
    # Output: a:  25 b:  4
    
  • Bitwise AND Assignment (&=): The Bitwise AND Assignment operator (&=) in Python combines bitwise AND operation with the assignment operator. It performs a bitwise AND between the left operand and the right operand, and then assigns the result back to the left operand. This is a shorthand way of performing bitwise AND operation and updating the value of the variable in a single step.

    Example: Bitwise AND Assignment Operator (&=)

    
    a = 6
    a &= 11  # equivalent to a = a & 11
    b = 9
    b &= 5  # equivalent to b = b & 5
    
    # USE THE ASSIGNMENT OPERATOR IN PYTHON
    print("a: ", a, "b: ", b)
    
    # Output: a:  2 b:  1
    
  • Bitwise OR Assignment (|=): The Bitwise OR Assignment (|=) operator in Python combines the bitwise OR operation and assignment. It performs a bitwise OR between the left operand and the right operand, and assigns the result back to the left operand. This is also a shorthand way of performing a bitwise OR operation and updating the value of the variable in a single step.

    Example: Bitwise OR Assignment Operator (|=)

    
    a = 6
    a |= 11  # equivalent to a = a | 11
    b = 9
    b |= 5  # equivalent to b = b | 5
    
    # USE THE ASSIGNMENT OPERATOR IN PYTHON
    print("a: ", a, "b: ", b)
    
    # Output: a:  15 b:  13
    
  • Bitwise XOR Assignment (^=): The Bitwise XOR Assignment operator (^=) in Python combines the bitwise XOR (exclusive OR) operation with the assignment operator. It performs a bitwise XOR between the left operand and the right operand and then assigns the result back to the left operand. This is also a shorthand way of performing such an operation and allows you to write a concise code when you want to perform a bitwise XOR operation and assign the result back to a variable.

    Example: Bitwise XOR Assignment Operator (^=)

    
    a = 6
    a ^= 11  # equivalent to a = a ^ 11
    b = 9
    b ^= 5  # equivalent to b = b ^ 5
    
    # USE THE ASSIGNMENT OPERATOR IN PYTHON
    print("a: ", a, "b: ", b)
    
    # Output: a:  13 b:  12
    
  • Right Shift Assignment (>>=): The Right Shift Assignment (>>=) operator in Python combines the right shift operation and assignment. It shifts the bits of the left operand to the right by the number of positions specified by the right operand, and assigns the result back to the left operand. This shorthand way of operations allows you to write a simple and concise code especially when you want to perform a right shift operation and assign the result back to a variable.

    Example: Right Shift Assignment Operator (>>=)

    
    a = 2
    a >>= 1  # equivalent to a = a >> 1
    b = 4
    b >>= 3  # equivalent to b = b >> 3
    
    # USE THE ASSIGNMENT OPERATOR IN PYTHON
    print("a: ", a, "b: ", b)
    
    # Output: a:  1 b:  0
    
  • Left Shift Assignment (<<=): The Left Shift Assignment operator (<<=) in Python combines the left shift operation with the assignment operator. It shifts the bits of the left operand to the left by the number of positions specified by the right operand and assigns the result back to the left operand. Similar to the previous purpose this helps us to write our code in a simple and concise way (shorthand way) while performing a left shift operation and assigning the result back to a variable in a single step.

    Example: Left Shift Assignment Operator (<<=)

    
    a = 2
    a <<= 1  # equivalent to a = a << 1
    b = 4
    b <<= 3  # equivalent to b = b << 3
    
    # USE THE ASSIGNMENT OPERATOR IN PYTHON
    print("a: ", a, "b: ", b)
    
    # Output: a:  4 b:  32
    
  • Bitwise NOT Assignment (~): you can combine the Bitwise NOT operator (~) with an assignment operator to perform a bitwise negation and assign the result back to a variable. It allows you to update the variable with the negated value in a single step. Note: Python does not have a specific “Bitwise NOT Assignment” (~=) operator. Unlike other assignment operators such as +=, -=, *=, etc., there is no direct equivalent for the bitwise negation operator combined with the assignment operator.

    Example: Bitwise NOT Assignment (~)

    
    a = 5
    b = ~a
    
    # USE THE ASSIGNMENT OPERATOR IN PYTHON
    print("a: ", a, "b:", b)
    a = ~a
    print("a: ", a)
    
    # Output: a:  5 b: -6
    # Output: a:  -6
    

Python Bitwise Operators

Bitwise operators perform operations on binary representations of integers. They are used to manipulate individual bits of numbers. Here is the list of bitwise operators found in Python:

  • Bitwise AND (&): Performs a bitwise AND operation between two operands. This is a common operator and performs a bitwise AND operation on the binary representations of two numbers. It then returns a new number where each bit is set to 1 only if the corresponding bits of both operands are 1.

    Example:

    
    # DISPLAY THE BINARY VALUE OF THESE VALUES
    
    print("The binary value of 5 is ",bin(5))
    print("The binary value of 3 is ",bin(3))
    print("The binary value of 4 is ",bin(4))
    print("The binary value of 7 is ",bin(7))
    
    # USE BITWISE OPERATOR (&) TO PERFORM OPERATION
    print("\nWHEN USED AND 5 & 3 =", 5 & 3) 
    print("WHEN USED AND 5 & 4 =", 5 & 4)
    print("WHEN USED AND 5 & 7 =", 5 & 7)
    
    # YOU CAN ALSO DISPPLAY AS FOLLOWS 
    
    print("\nWHEN USED AND 5 & 3 =", 5 & 3, "THE RESULT IN BINARY:", bin(5&3)) 
    print("WHEN USED AND 5 & 4 =", 5 & 4, "THE RESULT IN BINARY:",bin(5&4))
    print("WHEN USED AND 5 & 7 =", 5 & 7, "THE RESULT IN BINARY:",bin(5&7))
    
    """ Output:
    The binary value of 5 is  0b101
    The binary value of 3 is  0b11
    The binary value of 4 is  0b100
    The binary value of 7 is  0b111
    
    WHEN USED AND 5 & 3 = 1
    WHEN USED AND 5 & 4 = 4
    WHEN USED AND 5 & 7 = 5
    
    WHEN USED AND 5 & 3 = 1 THE RESULT IN BINARY: 0b1
    WHEN USED AND 5 & 4 = 4 THE RESULT IN BINARY: 0b100
    WHEN USED AND 5 & 7 = 5 THE RESULT IN BINARY: 0b101
    """
    
  • Bitwise OR (|): Performs a bitwise OR operation between two operands. This tells us when using such operator it performs a bitwise OR operation on the binary representations of two numbers. Then it will return a new number where each bit is set to 1 if at least one of the corresponding bits of either operand is 1.

    Example:

    
    # DISPLAY THE BINARY VALUE OF THESE VALUES
    
    print("The binary value of 5 is ",bin(5))
    print("The binary value of 3 is ",bin(3))
    print("The binary value of 4 is ",bin(4))
    print("The binary value of 7 is ",bin(7))
    
    # USE BITWISE OPERATOR (|) TO PERFORM OPERATION
    print("\nWHEN USED OR | 5 | 3 =", 5 | 3) 
    print("WHEN USED OR | 5 | 4 =", 5 | 4)
    print("WHEN USED OR | 5 | 7 =", 5 | 7)
    
    # YOU CAN ALSO DISPPLAY AS FOLLOWS 
    
    print("\nWHEN USED OR 5 | 3 =", 5 | 3, "THE RESULT IN BINARY:", bin(5|3)) 
    print("WHEN USED OR 5 | 4 =", 5 | 4, "THE RESULT IN BINARY:",bin(5|4))
    print("WHEN USED OR 5 | 7 =", 5 | 7, "THE RESULT IN BINARY:",bin(5|7))
    
    """ Output:
    The binary value of 5 is  0b101
    The binary value of 3 is  0b11
    The binary value of 4 is  0b100
    The binary value of 7 is  0b111
    
    WHEN USED OR | 5 | 3 = 7
    WHEN USED OR | 5 | 4 = 5
    WHEN USED OR | 5 | 7 = 7
    
    WHEN USED OR 5 | 3 = 7 THE RESULT IN BINARY: 0b111
    WHEN USED OR 5 | 4 = 5 THE RESULT IN BINARY: 0b101
    WHEN USED OR 5 | 7 = 7 THE RESULT IN BINARY: 0b111
    """
    
  • Bitwise XOR (^): Performs a bitwise XOR (exclusive OR) operation between two operands. This means a bitwise XOR (exclusive OR) performs an operation on the binary representations of two numbers. Then it returns a new number where each bit is set to 1 only if the corresponding bits of the operands differ (one is 0 and the other is 1).

    Example:

    
    # DISPLAY THE BINARY VALUE OF THESE VALUES
    print("The binary value of 5 is ",bin(5))
    print("The binary value of 3 is ",bin(3))
    print("The binary value of 4 is ",bin(4))
    print("The binary value of 7 is ",bin(7))
    
    # USE BITWISE OPERATOR (^) TO PERFORM OPERATION
    print("\nWHEN USED XOR 5 ^ 3 =", 5 ^ 3) 
    print("WHEN USED XOR 5 ^ 4 =", 5 ^ 4)
    print("WHEN USED XOR 5 ^ 7 =", 5 ^ 7)
    
    # YOU CAN ALSO DISPPLAY AS FOLLOWS 
    print("\nWHEN USED XOR 5 ^ 3 =", 5 ^ 3, "THE RESULT IN BINARY:", bin(5^3)) 
    print("WHEN USED XOR 5 ^ 4 =", 5 ^ 4, "THE RESULT IN BINARY:",bin(5^4))
    print("WHEN USED XOR 5 ^ 7 =", 5 ^ 7, "THE RESULT IN BINARY:",bin(5^7))
    
    """ Output:
    The binary value of 5 is  0b101
    The binary value of 3 is  0b11
    The binary value of 4 is  0b100
    The binary value of 7 is  0b111
    
    WHEN USED XOR 5 ^ 3 = 6
    WHEN USED XOR 5 ^ 4 = 1
    WHEN USED XOR 5 ^ 7 = 2
    
    WHEN USED XOR 5 ^ 3 = 6 THE RESULT IN BINARY: 0b110
    WHEN USED XOR 5 ^ 4 = 1 THE RESULT IN BINARY: 0b1
    WHEN USED XOR 5 ^ 7 = 2 THE RESULT IN BINARY: 0b10
    """
    
  • Bitwise NOT (~): Flips the bits of the operand. It performs a bitwise NOT operation on the binary representation of a number. It means it flips the bits, i.e., changes 0 to 1 and 1 to 0.

    Example:

    
    # DISPLAY THE BINARY VALUE OF THESE VALUES
    print("The binary value of 5 is ",bin(5))
    print("The binary value of 3 is ",bin(3))
    print("The binary value of 4 is ",bin(4))
    print("The binary value of 7 is ",bin(7))
    
    # USE BITWISE OPERATOR ~ TO PERFORM OPERATION
    print("\nWHEN USED Bitwise NOT (~) 5 =", ~5) 
    print("WHEN USED Bitwise NOT (~) 3 =", ~3)
    print("WHEN USED Bitwise NOT (~) 4 =", ~4)
    print("WHEN USED Bitwise NOT (~) 7 =", ~7)
    
    # YOU CAN ALSO DISPPLAY AS FOLLOWS 
    print("\nWHEN USED Bitwise NOT (~) 5 =", ~5, "THE RESULT IN BINARY:", bin(~5)) 
    print("WHEN USED Bitwise NOT (~) 3 =", ~3, "THE RESULT IN BINARY:",bin(~3))
    print("WHEN USED Bitwise NOT (~) 4 =", ~4, "THE RESULT IN BINARY:",bin(~4))
    print("WHEN USED Bitwise NOT (~) 7 =", ~7, "THE RESULT IN BINARY:",bin(~7))
    
    """ Output:
    The binary value of 5 is  0b101
    The binary value of 3 is  0b11
    The binary value of 4 is  0b100
    The binary value of 7 is  0b111
    
    WHEN USED Bitwise NOT (~) 5 = -6
    WHEN USED Bitwise NOT (~) 3 = -4
    WHEN USED Bitwise NOT (~) 4 = -5
    WHEN USED Bitwise NOT (~) 7 = -8
    
    WHEN USED Bitwise NOT (~) 5 = -6 THE RESULT IN BINARY: -0b110
    WHEN USED Bitwise NOT (~) 3 = -4 THE RESULT IN BINARY: -0b100
    WHEN USED Bitwise NOT (~) 4 = -5 THE RESULT IN BINARY: -0b101
    WHEN USED Bitwise NOT (~) 7 = -8 THE RESULT IN BINARY: -0b1000
    """
    
  • Right Shift (>>): Performs a right shift operation on the binary representation of a number. It shifts the bits to the right by a specified number of positions, and fills the vacant bits on the left with zeroes..

    Example:

    
    # DISPLAY THE BINARY VALUE OF THESE VALUES
    print("The binary value of 5 is ",bin(5))
    print("The binary value of 3 is ",bin(3))
    print("The binary value of 4 is ",bin(4))
    print("The binary value of 7 is ",bin(7))
    
    # USE BITWISE OPERATOR (>>) TO PERFORM OPERATION
    print("\nWHEN USED RIGHT SHIFT 5 >> 3 =", 5 >> 3) 
    print("WHEN USED RIGHT SHIFT 5 >> 4 =", 5 >> 4)
    print("WHEN USED RIGHT SHIFT 5 >> 7 =", 5 >> 7)
    
    # YOU CAN ALSO DISPPLAY AS FOLLOWS 
    print("\nWHEN USED RIGHT SHIFT 5 >> 3 =", 5 >> 3, "THE RESULT IN BINARY:", bin(5>>3)) 
    print("WHEN USED RIGHT SHIFT 5 >> 4 =", 5 >> 4, "THE RESULT IN BINARY:",bin(5>>4))
    print("WHEN USED RIGHT SHIFT 5 >> 7 =", 5 >> 7, "THE RESULT IN BINARY:",bin(5>>7))
    
    """ Output:
    The binary value of 5 is  0b101
    The binary value of 3 is  0b11
    The binary value of 4 is  0b100
    The binary value of 7 is  0b111
    
    WHEN USED RIGHT SHIFT 5 >> 3 = 0
    WHEN USED RIGHT SHIFT 5 >> 4 = 0
    WHEN USED RIGHT SHIFT 5 >> 7 = 0
    
    WHEN USED RIGHT SHIFT 5 >> 3 = 0 THE RESULT IN BINARY: 0b0
    WHEN USED RIGHT SHIFT 5 >> 4 = 0 THE RESULT IN BINARY: 0b0
    WHEN USED RIGHT SHIFT 5 >> 7 = 0 THE RESULT IN BINARY: 0b0
    """
    
  • Left Shift (<<): Performs a left shift operation on the binary representation of a number. It shifts the bits to the left by a specified number of positions, and fills the vacant bits on the right with zeroes.

    Example:

    
    # DISPLAY THE BINARY VALUE OF THESE VALUES
    print("The binary value of 5 is ",bin(5))
    print("The binary value of 3 is ",bin(3))
    print("The binary value of 4 is ",bin(4))
    print("The binary value of 7 is ",bin(7))
    
    # USE BITWISE OPERATOR << TO PERFORM OPERATION
    print("\nWHEN USED LEFT SHIFT 5 << 3 =", 5 << 3) 
    print("WHEN USED LEFT SHIFT 5 << 4 =", 5 << 4)
    print("WHEN USED LEFT SHIFT 5 << 7 =", 5 << 7)
    
    # YOU CAN ALSO DISPPLAY AS FOLLOWS 
    print("\nWHEN USED LEFT SHIFT 5 << 3 =", 5 << 3, "THE RESULT IN BINARY:", bin(5<<3)) 
    print("WHEN USED LEFT SHIFT 5 << 4 =", 5 << 4, "THE RESULT IN BINARY:",bin(5<<4))
    print("WHEN USED LEFT SHIFT 5 << 7 =", 5 << 7, "THE RESULT IN BINARY:",bin(5<<7))
    
    """ Output:
    The binary value of 5 is  0b101
    The binary value of 3 is  0b11
    The binary value of 4 is  0b100
    The binary value of 7 is  0b111
    
    WHEN USED LEFT SHIFT 5 << 3 = 40
    WHEN USED LEFT SHIFT 5 << 4 = 80
    WHEN USED LEFT SHIFT 5 << 7 = 640
    
    WHEN USED LEFT SHIFT 5 << 3 = 40 THE RESULT IN BINARY: 0b101000
    WHEN USED LEFT SHIFT 5 << 4 = 80 THE RESULT IN BINARY: 0b1010000
    WHEN USED LEFT SHIFT 5 << 7 = 640 THE RESULT IN BINARY: 0b1010000000
    """
    

Python Comparison Operators

Comparison operators are used to compare two values and determine their relationship. They return either True or False.

These comparison operators are commonly used in conditional statements, loops, and other scenarios where you need to compare values and make decisions based on the comparison results.

Here are the comparison operators n Python:

  • Equal to (==): The “==” operator checks if the values of two operands are equal. If the values are equal, it returns True; otherwise, it returns False.

    Example:

    
    # COMPARISION OPERATOR
    x = 5
    y = 10
    print(x == y)  
    
    # COMPARISION OPERATOR WITH IF AND ELSE STATEMENT
    a = "Python"
    b = "Java"
    
    if a==b:
        print("Both strings are equal")
    else:
        print("Both strings are not equal")
    
    """ Output: 
    False
    Both strings are not equal"""
    
  • Not equal to (!=): The “!=” operator checks if the values of two operands are not equal. If the values are different, it returns True; otherwise, it returns False.

    Example:

    
    # COMPARISION OPERATOR
    x = 5
    y = 10
    print(x != y)  
    
    # COMPARISION OPERATOR WITH IF AND ELSE STATEMENT
    a = "Python"
    b = "Java"
    
    if a!=b:
        print("Both strings are not equal")
    else:
        print("Both strings are equal")
    
    """ Output: 
    True
    Both strings are not equal"""
    
  • Greater than (>): The “>” operator checks if the value on the left side is greater than the value on the right side. If it is true, it returns True; otherwise, it returns False.

    Example:

    
    # COMPARISION OPERATOR
    x = 5
    y = 10
    print(x > y)  
    
    # COMPARISION OPERATOR WITH IF AND ELSE STATEMENT
    a = "Python"
    b = "Java"
    
    if a > b:
        print("a is greater than b")
    else:
        print("a is not greater than b")
    
    """ Output: 
    False
    a is greater than b"""
    
  • Less than (<): The “<” operator checks if the value on the left side is less than the value on the right side. If it is true, it returns True; otherwise, it returns False.

    Example:

    
    # COMPARISION OPERATOR
    
    x = 5
    y = 10
    
    print(x < y)  
    
    # COMPARISION OPERATOR WITH IF AND ELSE STATEMENT
    
    a = "Python"
    b = "Java"
    
    if a < b:
        print("a is less than b")
    else:
        print("a is not less than b")
    
    """ Output: 
    True
    a is not less than b"""
    
  • Greater than or equal to (>=): The “>=” operator checks if the value on the left side is greater than or equal to the value on the right side. If it is true, it returns True; otherwise, it returns False.

    Example:

    
    # COMPARISION OPERATOR
    x = 5
    y = 10
    print(x >= y)  
    
    # COMPARISION OPERATOR WITH IF AND ELSE STATEMENT
    a = "Python"
    b = "Java"
    
    if a >= b:
        print("a is geater than or equal to b")
    else:
        print("a is not greater or equal to b")
    
    """ Output: 
    False
    a is geater than or equal to b"""
    
  • Less than or equal to (<=): The “<=” operator checks if the value on the left side is less than or equal to the value on the right side. If it is true, it returns True; otherwise, it returns False.

    Example:

    
    # COMPARISION OPERATOR
    x = 5
    y = 10
    
    print(x <= y)  
    
    # COMPARISION OPERATOR WITH IF AND ELSE STATEMENT
    a = "Python"
    b = "Java"
    
    if a <= b:
        print("a is less than or equal to b")
    else:
        print("a is not less than or equal to b")
    
    """ Output: 
    True
    a is not less than or equal to b"""
    

Python Identity Operators

Identity operators are used to compare the memory locations of two objects. They return True or False based on the comparison. The identity operators in Python are:

  • “is”: Returns True if two variables or operands refer to the same object.

    Example:

    
    # is operator will return True if both operands are the same object	
    # USE IDENTITY OPERATOR IS TO SEE IF TWO OBJECTS ARE SAME OBJECT OR NOT USING PYTHON
    x= 10
    y = 10
    print(x is y)
    
    a = "Python"
    b = "Java"
    if a is b:
        print("BOTH OBJECTS ARE SAME")
    else:
        print("BOTH OBJECTS ARE NOT SAME")
    
    """ Output: True
    BOTH OBJECTS ARE NOT SAME"""
    
  • “is not”: Returns True if two variables refer to different objects.

    Example:

    
    # 'is not' operator will return True if both operands are not the same object	
    
    # USE IDENTITY OPERATOR IS NOT TO SEE IF TWO OBJECTS ARE SAME OBJECT OR NOT USING PYTHON
    
    x= 10
    y = 10
    print(x is not y)
    
    a = "Python"
    b = "Java"
    if a is not b:
        print("BOTH OBJECTS ARE NOT SAME")
    else:
        print("BOTH OBJECTS ARE SAME")
    
    """ Output: False
    BOTH OBJECTS ARE NOT SAME"""
    

Python Logical Operators

Logical operators are used to combine multiple conditions or values and perform logical operations. Here are the logical operators in Python:

  • Logical AND (and): Returns True if both operands are True.

    Example:

    
    # Use the 'and' logical operator to	return True if both statements are true	 
    # HOW TO USE LOGICAL OPERATOR AND TO CHECK MULTIPLE CONDITIONS IN PYTHON
    x = 20
    y = 30
    c = 0
    
    print(x and y)
    print(c and y)
    print(x == 30 and y)
    print(x == 20 and y > 20)
    
    a = "Python"
    b = "Java"
    
    if a < "Python3" and b > "Java":
        print("The all conditions are passed")
    else:
        print("Not all conditions are passed")
    
    """ Output: 
    30
    0
    False
    True
    Not all conditions are passed"""
    

    Note: The output of the code snippet x = 20; y = 30; print(x and y) would be 30.
    In Python, the and operator performs a logical AND operation on its operands. When used with non-boolean values, such as integers, the and operator evaluates the operands in a boolean context and returns the last evaluated operand. In this case, both x and y are non-zero integers, which are considered True in a boolean context. When the and operator is applied, it evaluates x first. Since x is non-zero (specifically, 20), it evaluates to True. Then, it proceeds to evaluate y. Since y is also non-zero (specifically, 30), it evaluates to True as well. According to the behavior of the and operator, it returns the last evaluated operand if all the operands evaluate to True. Hence, the expression x and y evaluates to 30, and that is what will be printed.

  • Logical OR (or): Returns True if at least one of the operands is True.

    Example:

    
    # Use the 'or' logical operator to return True if one statement is true	 
    # HOW TO USE LOGICAL OPERATOR OR TO CHECK MULTIPLE CONDITIONS IN PYTHON
    x = 20
    y = 30
    c = 0
    
    print(x or y)
    print(c or y)
    
    print(x == 30 or y)
    print(x == 20 or y > 20)
    
    a = "Python"
    b = "Java"
    
    if a > "Python3" or b != "Java":
        print("The all conditions are passed")
    else:
        print("Not all conditions are passed")
    
    """ Output: 
    20
    30
    30
    True
    Not all conditions are passed"""
    
  • Logical NOT (not): Returns the opposite of the operand’s truth value. The Logical NOT operator is useful when you need to negate a boolean value or evaluate the truth value of an expression in the opposite sense. It’s important to note that the Logical NOT operator works only on boolean values. If you apply it to non-boolean values, such as integers or strings, it will first convert the operand into a boolean and then negate its truth value.

    Example:

    
    # Use the 'not' logical operator to	return True if the result is False and vise versa	 
    
    # HOW TO USE LOGICAL OPERATOR NOT TO CHECK MULTIPLE CONDITIONS IN PYTHON
    x = 20
    y = 30
    c = 0
    d = not y
    
    print(not(x))
    print(not(c))
    print(not(d))
    
    print(not(x and y))
    print(not(c or y))
    
    print(not(x == 30 and y))
    print(not(x == 20 or y > 20))
    
    a = "Python"
    b = "Java"
    
    if not(a > "Python3" or b != "Java"):
        print("The all conditions are passed")
    else:
        print("Not all conditions are passed")
    
    """ Output: 
    False
    True
    True
    False
    False
    True
    False
    The all conditions are passed"""
    

Python Membership Operators

Membership operators are used to test whether a value or variable is a member of a sequence (string, list, tuple, etc.). Membership operators are commonly used in conditional statements to check if a value is present in a list, tuple, string, or any other iterable object. They allow you to test the inclusion or exclusion of values in a convenient way. The membership operators in Python are:

  • “in”: The “in” operator checks if a value or variable exists as a member within a sequence. It returns True if the value is found in the sequence, and False otherwise.

    Example: Using the Python Membership Operator ‘in’ for Sequence Checking

    
    """
    How to use the Python Membership Operator 'in'
    in membership operator is used to checks if a value or variable exists as a member within a sequence
    if a sequence with the specified value is present in the object it will return True otherwise False
    """
    # USE IN OPERATOR IF A SPECIFIC VALUE FROM ONE SET IS PRESENT IN ANOTHER SET VARIABLE USING PYTHON
    a = ["Java","Python","C++"]
    b = ["C","Java","Python"]
    
    x = {2,4,5,7,8,9}
    y = 2 in x
    
    e = "Hello"
    
    print("Java" in a)
    print(y)
    print("Hell" in e)
    print("He1ll" in e)
    
    """ Output: 
    True
    True
    True
    False
    """
    

    Example: Another code snippet about Python Membership Operator ‘in’ for Sequence Checking

    
    """
    Another Example using in operator
    """
    a = ["Java", "Python", "C++"]
    c = ["Java", "Python", "C++"] in a
    
    print(c)  # Output: False
    
    

    Check the above example and the result will be False. here is why. First of all, The variable a is assigned a list containing three elements: "Java", "Python", and "C++". The statement ["Java", "Python", "C++"] in a checks if the list ["Java", "Python", "C++"] is an element of the list a.
    In other words, it checks if the entire list ["Java", "Python", "C++"] appears as a single element in the list a. Since the list ["Java", "Python", "C++"] is not a single element in the list a, the expression evaluates to False. As a result, the variable c is assigned the value False. Therefore, when print(c) is executed, it outputs False.

    Example: This code snippet will trigger an error and it is about Python Membership Operator ‘in’ for Sequence Checking

    
    """
    Another Example using in operator
    """
    x = 2
    y = 2 in x
    
    print(y)
    
    

    The code snippet provided above x = 2; y = 2 in x; print(y) cannot be executed as it would raise a TypeError because the membership operator 'in' expects a sequence or collection on its right-hand side, but an integer (x = 2) is provided instead. The membership operator 'in' is used to check if a value is present in a sequence (such as a list, tuple, set, or string). It cannot be directly applied to a single value or an integer. If you want to check if a value is equal to another value, you can use the equality operator (==). Here’s an example:

    
    """
    Another Example without the in operator
    """
    x = 2
    y = 2 == x
    print(y)  # Output: True
    
    
  • “not in”: The “not in” operator checks if a value or variable does not exist as a member within a sequence. It returns True if the value is not found in the sequence, and False if it is found.

    Example: Using the Python Membership Operator ‘not in’ for Sequence Checking

    
    """
    How to use the Python Membership Operator 'not in'
    not in membership operator is used to checks if a value or variable does not exist as a member within a sequence
    if a sequence with the specified value is not present in the object it will return True otherwise False
    """
    # USE NOT IN OPERATOR IF A SPECIFIC VALUE FROM ONE SET IS NOT PRESENT IN ANOTHER SET VARIABLE USING PYTHON
    a = ["Java","Python","C++"]
    b = ["C","Java","Python"]
    
    x = {2,4,5,7,8,9}
    y = 2 not in x
    
    e = "Hello"
    
    print("Java" not in a)
    print(y)
    print("Hell" not in e)
    print("He1ll" not in e)
    
    """ Output: 
    True
    True
    True
    False
    """
    
    

Conclusion

In conclusion, we have discussed various Python operators that serve different purposes in programming. Here we summarize our discussed Python operator in this article:

  1. Arithmetic Operators: These operators perform arithmetic operations on numeric values, such as addition (+), subtraction (-), multiplication (*), division (/), modulus (%), floor division (//), and exponentiation (**).
  2. Assignment Operators: Assignment operators are used to assign values to variables. They include the basic assignment operator (=) and compound assignment operators like +=, -=, *=, /=, %=, //=, **=, &=, |=, ^=, >>=, and <<=.
  3. Comparison Operators: Comparison operators are used to compare two values and return a boolean result. They include equal to (==), not equal to (!=), greater than (>), less than (<), greater than or equal to (>=), and less than or equal to (<=).
  4. Logical Operators: Logical operators are used to combine and evaluate multiple boolean expressions. They include and, or, and not, which perform logical AND, logical OR, and logical NOT operations, respectively.
  5. Bitwise Operators: Bitwise operators perform operations on binary representations of integers. They include bitwise AND (&), bitwise OR (|), bitwise XOR (^), bitwise NOT (~), left shift (<<), and right shift (>>).
  6. Membership Operators: Membership operators are used to test if a value or variable is a member of a sequence. They include in and not in, which return True or False based on the presence or absence of the specified value in the sequence.

Each operator category has its specific use case and syntax. Understanding these operators allows you to perform various calculations, comparisons, and manipulations in your Python programs efficiently. By utilizing these operators effectively, you can write concise and expressive code to solve a wide range of problems.

Categorized in: