Operators

What Are Operators?

  • Operators are used to perform operations on variables and values. For example, using the + operator to add two numbers: print(10 + 5).

Types of Operators:

  1. Arithmetic Operators:

    • Used to perform common mathematical operations.
    OperatorNameExample
    +Additionx + y
    -Subtractionx - y
    *Multiplicationx * y
    /Divisionx / y
    %Modulusx % y
    **Exponentiationx ** y
    //Floor divisionx // y
  2. Assignment Operators:

    • Used to assign values to variables.
    OperatorExampleSame As
    =x = 5x = 5
    +=x += 3x = x + 3
    -=x -= 3x = x - 3
    *=x *= 3x = x * 3
    /=x /= 3x = x / 3
    %=x %= 3x = x % 3
    //=x //= 3x = x // 3
    **=x **= 3x = x ** 3
    &=x &= 3x = x & 3
     =x
    ^=x ^= 3x = x ^ 3
    >>=x >>= 3x = x >> 3
    <<=x <<= 3x = x << 3
  3. Comparison Operators:

    • Used to compare two values.
    OperatorNameExample
    ==Equalx == y
    !=Not equalx != y
    >Greater thanx > y
    <Less thanx < y
    >=Greater than or equal tox >= y
    <=Less than or equal tox <= y
  4. Logical Operators:

    • Used to combine conditional statements.
    OperatorDescriptionExample
    andReturns True if both statements are truex < 5 and x < 10
    orReturns True if one of the statements is truex < 5 or x < 4
    notReverses the result, returns False if the result is truenot(x < 5 and x < 10)
  5. Identity Operators:

    • Used to compare objects, not if they are equal, but if they are the same object with the same memory location.
    OperatorDescriptionExample
    isReturns True if both variables are the same objectx is y
    is notReturns True if both variables are not the same objectx is not y
  6. Membership Operators:

    • Used to test if a sequence is present in an object.
    OperatorDescriptionExample
    inReturns True if a sequence with the specified value is present in the objectx in y
    not inReturns True if a sequence with the specified value is not present in the objectx not in y

Operator Precedence:

  • Operator precedence determines the order in which operations are performed. Parentheses () have the highest precedence, followed by exponentiation **, and so on.

Example:

  • Addition and subtraction have the same precedence, so we evaluate the expression from left to right.

    python
    print(5 + 4 - 7 + 3)  
    
    • Output: 5

Summary:

  • Python provides a variety of operators to perform operations on variables and values. Understanding these operators and their precedence is essential for writing effective and efficient code. Practice using these operators to master their usage in Python!