Skip to content
Home » How to Calculate a Percent Change Using Python

How to Calculate a Percent Change Using Python

Spread the love

To calculate a percent change, you can use the following formula:

pc = (new – old) / old * 100%

where old and new are the values before and after change respectively.

percent change

Here’s how we can implement it in Python:

>>> def percent_change(old, new):
...     pc = round((new - old) / abs(old) * 100, 2)
...     print(f"from {old} to {new}   -> {pc}% change")
... 

Watch the built-in abs function inside the percent_change function. Without it you would get wrong results if the old value was negative.

Here’s how it works:

>>> percent_change(60, 60)
from 60 to 60   -> 0.0% change
>>> percent_change(100, 120)
from 100 to 120   -> 20.0% change
>>> percent_change(100, 80)
from 100 to 80   -> -20.0% change
>>> percent_change(50, -50)
from 50 to -50   -> -200.0% change
>>> percent_change(-20, 20)
from -20 to 20   -> 200.0% change
>>> percent_change(-20, -50)
from -20 to -50   -> -150.0% change

Your Panda3D Magazine

Make Awesome Games and Other 3D Apps

with Panda3D and Blender using Python.

Cool stuff, easy to follow articles.

Get the magazine here (PDF).

Python Jumpstart Course

Learn the basics of Python, including OOP.

with lots of exercises, easy to follow

The course is available on Udemy.

Blender Jumpstart Course

Learn the basics of 3D modeling in Blender.

step-by-step, easy to follow, visually rich

The course is available on Udemy and on Skillshare.

Here’s the video version of the article:


Spread the love

Leave a Reply