Skip to content

Python percentage difference between two numbers | Example code

  • by

You can use a math formula to find the percentage difference between two numbers in Python. Percentage Difference = |(Number1 – Number2) / ((Number1 + Number2) / 2)| * 100.

Formula to calculate percentage:

(Percentage2 – Percentage1) * 100 / (Percentage1) 

Example percentage difference between two numbers in Python

A simple example code finds the percentage of the difference between two numbers.

a = 10
b = 15

result = int(((b - a) * 100) / a)

print(result, "%")

Output: 50 %

User input number

first = int(input("Enter first number: "))
second = int(input("Enter second number:"))

res = ((first - second) / first) * 100

print("Difference in percentage is : {}%".format(res))

Output:

Python percentage difference between two numbers
def percentage_difference(number1, number2):
    if number1 == number2:
        return 0  # The numbers are the same, so the percentage difference is 0.

    # Calculate the percentage difference using the formula
    percentage_diff = abs((number1 - number2) / ((number1 + number2) / 2)) * 100
    return percentage_diff

# Example usage
number1 = 50
number2 = 60

percentage_diff = percentage_difference(number1, number2)
print(f"The percentage difference between {number1} and {number2} is {percentage_diff:.2f}%")

In this code, the percentage_difference function takes two numbers as input and calculates the percentage difference using the formula. It first checks if the two numbers are equal, in which case the percentage difference is 0. Otherwise, it calculates the percentage difference and returns the result.

You can replace number1 and number2 with your own values to calculate the percentage difference between any two numbers.

Do comment if you have any doubts or suggestions on this Python number topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading