To decrement a counter in Python, you can use the -= decrement operator and subtract a number from the counter.
i = 0
i -= 1
print(i)
#Output:
-1
The decrement operator is the equivalent of subtracting a number via simple subtraction.
i = 0
i = i - 1
print(i)
#Output:
-1
In Python, counters are frequently used when iterating over an object or keeping track of a count for later use.
There are many useful operators in Python and one such operator which makes counting easy is the decrement operator -=.
You can use the -= to subtract a number to another number and decrement a counter.
For example, if you want to subtract one from a number and decrement a counter, you can do so with the following Python code.
i = 0
i -= 1
print(i)
#Output:
-1
This is the equivalent as using simple subtraction to subtract from a number.
i = 0
i = i + 1
print(i)
#Output:
1
You can subtract any number with the decrement operator including floats.
i = 0
i -= 2
print(i)
i -= 2.0
print(i)
#Output:
-2
-4.0
Increment Counter in Python with Increment Operator +=
If you want to go the other way and increment a counter, then you can use the Python increment operator +=.
The increment operator works the same as the decrement operator.
Below shows you a simple example of how you can increment a counter in Python with the increment operator.
i = 0
i += 1
print(i)
#Output:
1
Hopefully this article has been useful for you to learn how to use the decrement operator and how to decrement a counter in Python.