Skip to content

Increment and Decrement

Posted by James Simms on November 26, 2019

So, in the second little video short on Python (Twitter/YouTube), we looked at how to efficiently increment (add to) and decrement (subtract from) variable values in Python.

In this tutorial, I'll be using Python 3.8 with the IDLEX extensions installed.

When we are working with Integers, or floats, in Python, sometimes we need to increment (which means to add to) or decrement (which means to subtract from) their value. For example, let's create a variable houses and give it the initial value 9 ...

>>> houses = 9

 

We acquire another house in our portfolio, so we need to increment the value. We might do it like this ...

>>> houses = houses + 1
>>> print(houses)
10

 

However, there is a quicker way of incrementing it's value ...

>>> houses += 1
>>> print(houses)
11

 

The += is called an incrementation operator. Now, let's say that I've 100 mice in my mouse collection ...

>>> mice = 100

 

But unfortunately, one of them dies. We can decrement, or reduce, the value of mice in a similar way ...

>>> mice -= 1
>>> print(mice)
99

 

The -= is called a decrementation operator. We don't have to increment, or decrement, by 1. We can use other numbers as well.

>>> houses += 7
>>> mice -= 5
>>> print(houses)
18
>>> print(mice)
94

 

We can also use a variable or a constant for the value to increment or decrement by. For instance ...

>>> step = 3
>>> tweets = 97
>>> tweets += step
>>> print(tweets)
100

 

That's a lot of tweets!