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.
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
Here’s the video version of the article: