Why Use the += Symbol?


Why did they add a “+=” symbol after annual_rainfall here??

FAQ: Learn Python - Python Syntax - Updating Variables

Hi @aneesh469,

+= is the syntax used to add a value to a variable’s existing value. It’s a shorter form of something like this:

total = total + 2


+= is one of a special group known as assignment operators.

The operator does not manipulate the value on the left side, but replaces it with the evaluation of the expression on the right This means we can mutate strings (sort of) …

var a = "";
a += "hello";
a += " ";
a += "world";

console.log(a)    // <- hello world

Strings are by definition immutable but since we are not changing the string, only replacing it, it takes on the appearance of mutation.


I’m still a bit confused. I don’t understand why, in this particular exercise, they didn’t add the syntax to all of the months then, if at the end of the year it would be added together and this lesson is to learn how to update as data changes. They used it twice, but why in the particular spot that they did. Is it just random and you can choose where to put it or decide to use that syntax at all. Such as the first time they used it, annual_rainfall += july_rainfall. How do I know where to use this syntax? The definition of the syntax by zystvan; += means total = total + 2 (What does the 2 mean?)


In algebra we would never write:

a = a + 1

That’s because in math the above is treated as an equation, and as such cannot be true by any Real logic. It throws people the first time they see it in programming.

a = a + 1

is an assignment that tells the interpreter to increase the value of a by 1. The assignment is always from right to left, so a + 1 is first evaluated (computed) and the result assigned back onto the same variable. Now a has a different reference.

a += 1

is the earlier statement rolled into a simpler assigment syntax. Behind the scenes the same process is rolling out…evaluate and assign.

Ultimately, since they both do the same thing it really does not matter which form of expression we use. Use what suits one. Eventually, though, the shorter syntax will be the one that sticks as the needs arise.

Be sure to look up all the Python arithmetic and assignment operators so you learn the complete range.