
Augmented assignment statement
First, examine the following code.
num = 3
num = num + 6 # Add 6 to num and overwrite the value.
print(num) # 9 is output
First, the variable num is assigned the value 3. In the second line, the variable num is added to 6 and assigned (overwritten). The output result is 9. This code is written in the same way as we have learned so far.
The expression in the second line above can be written using an augmented assignment statement. It can be rewritten as follows.
num = 3
num += 6 # Add 6 to num and overwrite the value.
print(num) # 9 is output
The change in the above code is in the second line, where “num += 6” has been replaced with the symbol combination “+=
”. This is equivalent to “num = num + 6”. In other words, it means, “Add the value on the right side to the value on the left side (the variable) and assign the result back to the left side.” Writing it this way simplifies the code. (Note: Writing “num = num + 6” is also correct.)
Augmented assignment statements can be used in expressions such as “a = a + b” and can be used with any operator other than the +
sign.
num += 5 # num = num + 5
num -= 5 # num = num - 5
num *= 5 # num = num * 5
num /= 5 # num = num / 5
num %= 5 # num = num % 5
num //= 5 # num = num // 5
num **= 5 # num = num ** 5
An example of where augmented assignment statements can be used is when counting the number of items that satisfy a certain condition, incrementing the value of the “count” variable by 1 each time an item that satisfies the condition is found. The code below is a program that counts the number of values in a list of height values that are greater than or equal to 2.0. It may not seem easy because there are many expressions that you have not learned yet, but try to identify where augmented assignment statements are used.
height_list = [0, 6.4, 5, 1.2, 0.8, 2.6]
count = 0 # The default value is 0.
for height in height_list:
if height > 2.0:
count += 1 # Here, increase count by 1.
print('Count is', count)
The important point to note in this code is that the value of the variable count, which was initialized to 0 in line 3, is incremented by 1 in line 6. The if statement in line 5 checks whether the height is 2.0 or more. If the condition is met, the value is incremented by “count += 1”. This is an example of using an augmented assignment statement.
Increment means to increase the value of a variable by 1, and decrement means to decrease the value of a variable by 1.
In Python, “num += 1” is an increment expression, and “num -= 1” is a decrement expression.
(※ In other programming languages, operators such as “num++” and “num--” are used, but Python does not have such operators.)