new to python and trying to wrestle with the finer points of assignment operators. Here's my code and then the question.
x = 5
print(x)
x -= x + 4
print(x)
the above code, returns 5 the first time, but yet -4 upon the second print. In my head I feel that the number should actually be 4 as I am reading this as x= x - x +4. However, I know that is wrong as python is returning -4 instead. I would be gracious if anyone could explain to me (in simple terms as I am a novice) as I have been really pounding my head over the table on this one.
The "common knowledge" of programming is that x += y is an equivalent shorthand notation of x = x + y . As long as x and y are of the same type (for example, both are int s), you may consider the two statements equivalent.
Let's understand the += operator in Java and learn to use it for our day to day programming. x += y in Java is the same as x = x + y. It is a compound assignment operator. Most commonly used for incrementing the value of a variable since x++ only increments the value by one.
The Python += operator adds two values together and assigns the final value to a variable. This operator is called the addition assignment operator. This operator is often used to add values to a counter variable that tracks how many times something has happened.
The addition assignment operator ( += ) adds the value of the right operand to a variable and assigns the result to the variable. The types of the two operands determine the behavior of the addition assignment operator.
x -= x + 4
can be written as:
x = x - (x + 4) = x - x - 4 = -4
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With