Skip to main content

How to calculate a Percentage in Python

Calculating percentages is a fundamental task in many applications.

This guide explores various methods to calculate percentages in Python, including rounding, handling potential errors, calculating percentage increase/decrease, working with user input, and formatting percentage values.

Basic Percentage Calculation​

To calculate what percentage one number is of another, use the following formula: (number_a / number_b) * 100.

def is_what_percent_of(num_a, num_b):
return (num_a / num_b) * 100

print(is_what_percent_of(25, 75)) # Output: 33.333333333333336
print(is_what_percent_of(15, 93)) # Output: 16.129032258064516

The function is_what_percent_of takes two numbers as input and returns the percentage of the first number with respect to the second.

Rounding to a Specific Number of Decimal Places​

Use the round() function to limit the number of digits after the decimal point in your percentage calculation:

def is_what_percent_of(num_a, num_b):
return (num_a / num_b) * 100

print(round(is_what_percent_of(15, 93), 2)) # Output: 16.13
print(round((33 / 65) * 100, 2)) # Output: 50.77

The second argument to the round function indicates how many digits after the decimal point the result should have.

Handling ZeroDivisionError​

Division by zero causes a ZeroDivisionError. Handle it with a try/except block:

def is_what_percent_of(num_a, num_b):
try:
return (num_a / num_b) * 100
except ZeroDivisionError:
return 0

print(is_what_percent_of(25, 0)) # Output: 0

This returns 0 if a ZeroDivisionError occurs. You can customize the except block to return a different value, log the error or raise it.

Calculating Percentage Increase/Decrease​

Use the following formula to calculate the percentage increase or decrease between two numbers: ((number_a - number_b) / number_b) * 100

def get_percentage_increase(num_a, num_b):
return ((num_a - num_b) / num_b) * 100

print(get_percentage_increase(60, 30)) # Output: 100.0
print(get_percentage_increase(40, 100)) # Output: -60.0

A positive result means percentage increase and a negative result means a percentage decrease.

1. Using abs() for Absolute Percentage Difference​

Use the abs() function to always get a positive result, showing the absolute difference in percentage:

def get_percentage_increase(num_a, num_b):
return abs(((num_a - num_b) / num_b) * 100)

print(get_percentage_increase(60, 30)) # Output: 100.0
print(get_percentage_increase(40, 100)) # Output: 60.0

2. Handling Division by Zero​

If you want to handle ZeroDivisionError you can add a try/except block:

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


print(get_percentage_increase(60, 0)) # Output: inf
print(get_percentage_increase(60, 60)) # Output: 0.0
print(get_percentage_increase(60, 120)) # Output: 50.0

This returns infinity (inf) if a ZeroDivisionError occurs. You can customize this according to your need.

Understanding the Modulo Operator (%)​

The modulo operator % returns the remainder from integer division. Although it's not directly used to compute percentages it can be useful in other percentage-related tasks.

def get_remainder(num_a, num_b):
return num_a % num_b


print(get_remainder(50, 15)) # Output: 5
print(get_remainder(50, 20)) # Output: 10

print(10 % 2) # Output: 0
print(10 % 4) # Output: 2

The modulo operator is useful when you need to get the remainder from division.

Calculating Percentages from User Input​

To take user input and perform percentage calculations, first convert input to floats using float():

def is_what_percent_of(num_a, num_b):
return (num_a / num_b) * 100


num1 = float(input('Enter a number: '))
num2 = float(input('Enter another number: '))
result = is_what_percent_of(num1, num2)
print(result)
print(round(result, 2))

The input() method is guaranteed to return a string, even if the user enters a number. So, you must convert it to a floating point number using float() constructor.

Calculating Percentage Increase/Decrease from User Input​

To get the percentage increase from one number to another using input from the user, use the following code:

def get_percentage_increase(num_a, num_b):
return ((num_a - num_b) / num_b) * 100

num1 = float(input('Enter a number: '))
num2 = float(input('Enter another number: '))
result = get_percentage_increase(num1, num2)
print(result)
print(round(result, 2))
note

Remember to convert user input to floats before use.

Formatting Percentage Values​

Use f-strings to format percentage output with desired decimal precision:

user_input = input('Type a percentage, e.g. 10: ')
result_formatted_1 = f'{float(user_input) / 100:.1%}'
result_formatted_2 = f'{float(user_input) / 100:.2%}'

print(result_formatted_1) # Output: 10.0%
print(result_formatted_2) # Output: 10.00%

my_float = 0.79
print(f'{my_float:.1%}') # Output: 79.0%
print(f'{my_float:.2%}') # Output: 79.00%

The format specifier within the f-string :.N% specifies N decimal digits and adds the percent sign at the end.