What is the difference between = and +=?
I've been experimenting, and I haven't found the difference.
Similar to many other languages, += is a "shortcut".
x = y
Assigns a reference to the object on the right-hand-side to the name on the left.
x += y
Conceptually adds the object or the right-hand-size to the object referred to on the left. Conceptually the same as:
x = x + y
I say "conceptually" because the += operator can do different things depending on the class of the object on the left. For example with an integer it simply does an add, with a string (str) it appends to the string, with a list it adds a new element to the right side of the list.
A class can implement the __iadd__() special function which will carry to the required operation. += is a member of augmented assignments, see http://legacy.python.org/dev/peps/pep-0203/
In python, the phrase x=4 will assign the value of 4 to x. However, the phrase x+=4 will increment 4 to the current value of x. For example:
x = 3
print x #will print 3
x += 2
print x #will print 5
foo = bar sets foo to the same value as bar- if foo is 5 and bar is 3, foo is now 3.
foo += bar is shorthand for foo = foo + bar. So if foo is 5, and bar is 3, foo is now 8
This does in fact use whatever + means in context, so if foo is "A String" and bar is "bar", foo += bar makes foo == "A Stringbar"
x = 2 assigns a value 2 to the variable x. x += 2 is the same as x = x + 2. In other words += adds a value to a already existing value. Example:
>>> x += 2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'y' is not defined
This is because x has never been assigned to a value. To understand what happens, look at the following code:
>>> x = 2
>>> print(x)
2
>>> x += 2
>>> print(x)
4
In python
c = a + b assigns value of a + b into c
c = 1 + 3 #returns 4
c += a is equivalent to c = c + a
c = 1
a = 2
c += 1 #returns 3
Check out: http://www.tutorialspoint.com/python/python_basic_operators.htm
Quick Notes:
a=b : assign the value b to the variable a
a+=b : sum b to the current value of a
a+=b is a short notation for a = a + b
You can do a-=b, it'll reproduces a = a - b
you can either to *= , /= and %=
Example:
i = 2
i += 3
print i
# output = 5 (2+3)
i -= 3
print i
# output = 2 (5-3)
i *= 3
print i
# output = 6 (2*3)
i /= 3
print i
# output = 2 (6/3)
i %= 3
print i
# output = 2 (modulo of 2/3 = 2)
+=is a short notation for adding a value to the variable. Lets say ifx=1, thenx += 1will add 1 to x, so when you print x, it should say2x += 5is the same asx = x + 5=and+=would appear to be doing the same thing is if the variable on the left is already assigned to either0,[],{}, or''.