Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why does x -= x + 4 return -4 instead of 4

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.

like image 265
prance Avatar asked Oct 15 '15 03:10

prance


People also ask

What does x += y mean?

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.

Is it += or =+ in Java?

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.

How does += work in Python?

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.

What does += mean in Javascript?

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.


1 Answers

x -= x + 4 can be written as:

x = x - (x + 4) = x - x - 4 = -4
like image 168
Zarwan Avatar answered Oct 20 '22 00:10

Zarwan