In this session, we’ll look at Python’s += operator. Let us see how it works with a few simple examples.
The addition assignment operator is denoted by the operator ‘+=’. It is like a short form to it. It adds two values and stores the result in a variable (left operand).
Addition of Two numbers Using += Operator:
Example1:
gvn_num = 100
print("The given number = ", gvn_num)
gvn_num += 50
print("The given number after addition with 50 = ", gvn_num)
Output:
The given number = 100 The given number after addition with 50 = 150
Example2:
a = 10
b = 20
c = 30
rslt_sum = 0
# Adding a,b,c and storing it in a variable rslt_sum
# The below indicates rslt_sum = rslt_sum+(a+b+c)
rslt_sum += a+b+c
print("The sum of a,b,c = ", rslt_sum)
Output:
The sum of a,b,c = 60
For Strings
The ‘+=’ operator concatenates the given strings. It is used for the concatenation of two or more strings.
Example1:
gvn_fststr = "hello"
gvn_scndstr = "btechgeeks"
print("The given first string = ", gvn_fststr)
print("The given second string = ", gvn_scndstr)
print()
# It concatenates the given first string with the second string and assigns the
# result to the first string
gvn_fststr += gvn_scndstr
print("The given first string after concatenation = ", gvn_fststr)
Output:
The given first string = hello The given second string = btechgeeks The given first string after concatenation = hellobtechgeeks
Example2:
gvn_fststr = "hello"
gvn_scndstr = " this is "
gvn_thrdstr = "btechgeeks"
concat_str = ""
# concatenating the given three strings using '+=' Operator
concat_str += (gvn_fststr+gvn_scndstr+gvn_thrdstr)
print("The concatenation of given three strings = ", concat_str)
Output:
The concatenation of given three strings = hello this is btechgeeks
The “+=” operator’s Associativity in Python
The ‘+=’ operator’s associativity property is from right to left.
Example1:
a = 3
b = 6
a += b >> 2
print("a =", a)
print("b =", b)
Output:
a = 4 b = 6
Explanation:
We set the starting values of two variables, a and b, to 3 and 6, respectively. In the code, we right shift the value of b by two bits, add the result to variable ‘a’, and put the final result in variable ‘a’.
Therefore the final output is :
a=4 and b=6
Example2:
a = 3
b = 6
# Left shift by 1 bit
a += b << 1
print("a =", a)
print("b =", b)
Output:
a = 15 b = 6
Conclusion
This is about the Python ‘+=’ operator and its numerous implementations.