How to Calculate a Percentage in Python

How to Calculate a Percentage in Python

Calculating Percentages in Python. Percentages are a common way to represent parts of a whole. In Python, there are several ways to calculate percentages.

Calculating Percentages in Python

Percentages are a common way to represent parts of a whole. In Python, there are several ways to calculate percentages.

Basic Percentage Calculation

To calculate the percentage of one number relative to another, you can use the following formula:

percentage = (part / whole) * 100

Where part is the number you want to find the percentage of, and whole is the total number.

For example, to find the percentage of 25 out of 50, you would use the following code:

percentage = (25 / 50) * 100
print(percentage)

This would print the following output:

50.0

Percentage Increase or Decrease

To calculate the percentage increase or decrease between two numbers, you can use the following formula:

percentage_change = ((new - old) / old) * 100

Where new is the new number, and old is the old number.

For example, to find the percentage increase from 40 to 100, you would use the following code:

percentage_change = ((100 - 40) / 40) * 100
print(percentage_change)

This would print the following output:

150.0

Formatting Percentage Values

You can format percentage values using Python's f-strings. For example, to format a percentage value to two decimal places, you would use the following code:

percentage = 0.79
formatted_percentage = f"{percentage:.2%}"
print(formatted_percentage)

This would print the following output:

79.00%

Handling Division by Zero

If you try to divide by zero, you will get a ZeroDivisionError. To handle this error, you can use a try-except block. For example, the following code would print "Infinity" if you try to divide by zero:

def get_percentage_increase(num_a, num_b):
        try:
            return abs((num_a - num_b) / num_b) * 100
        except ZeroDivisionError:
            return float('inf')

Hope you will like this tutorial!!!

# Details

Published on January 31, 2024 2 min read

Python