Search code examples
pythonoperatorssymbols

^=, -= and += symbols in Python


I am quite experienced with Python, but recently, when I was looking at the solutions for the codility sample tests I encountered the operators -=, +=, ^= and I am unable to figure out what they do. Perhaps could anyone explain the context in which they are used?


Solution

  • As almost any modern language, Python has assignment operators so they can use them every time you want to assign a value to a variable after doing some arithmetic or logical operation, both (assignment and operation) are expressed in a compact way in one statement...

    Table from Tutorials Point:

    Operator Description Example
    = Assigns values from right side operands to left side operand c = a + b assigns value of a + b into c
    += Add AND It adds right operand to the left operand and assign the result to left operand c += a is equivalent to c = c + a
    -= Subtract AND It subtracts right operand from the left operand and assign the result to left operand c -= a is equivalent to c = c - a
    *= Multiply AND It multiplies right operand with the left operand and assign the result to left operand c *= a is equivalent to c = c * a
    /= Divide AND It divides left operand with the right operand and assign the result to left operand c /= a is equivalent to c = c / a
    %= Modulus AND It takes modulus using two operands and assign the result to left operand c %= a is equivalent to c = c % a
    **= Exponent AND Performs exponential (power) calculation on operators and assign value to the left operand c **= a is equivalent to c = c ** a
    //= Floor Division It performs floor division on operators and assign value to the left operand c //= a is equivalent to c = c // a