How to calculate a Percentage in Python

avatar
Borislav Hadzhiev

Last updated: Apr 9, 2024
5 min

banner

# Table of Contents

  1. Calculate percentage in Python
  2. Rounding to N digits after the decimal when calculating a percentage
  3. Getting the percentage increase/decrease between two numbers
  4. Calculate a Percentage from User Input in Python
  5. Calculate a Percentage Increase/Decrease from User Input in Python
  6. Formatting a Percentage Value

# Calculate percentage in Python

To calculate a percentage in Python:

  1. Use the division / operator to divide one number by another.
  2. Multiply the quotient by 100 to get the percentage.
  3. The result shows what percent the first number is of the second.
main.py
def is_what_percent_of(num_a, num_b): return (num_a / num_b) * 100 print(is_what_percent_of(25, 75)) # ๐Ÿ‘‰๏ธ 33.33 print(is_what_percent_of(15, 93)) # ๐Ÿ‘‰๏ธ 16.12903.. print(round(is_what_percent_of(15, 93), 2)) # ๐Ÿ‘‰๏ธ 16.13

calculate percentage in python

The code for this article is available on GitHub

The function takes 2 numbers and returns what percent the first number is of the second.

For example, 25 / 50 * 100 shows that 25 is 50% of 50.

main.py
print((25 / 50) * 100) # ๐Ÿ‘‰๏ธ 50.0

# Rounding to N digits after the decimal when calculating a percentage

When calculating percentages, you might need to round to a specific number of digits after the decimal.

The round function takes the following 2 parameters:

NameDescription
numberthe number to round to ndigits precision after the decimal
ndigitsthe number of digits after the decimal the number should have after the operation (optional)
main.py
print(round((33 / 65) * 100, 2)) # ๐Ÿ‘‰๏ธ 50.77
The code for this article is available on GitHub
The round function returns the number rounded to ndigits precision after the decimal point.

If ndigits is omitted, the function returns the nearest integer.

Note that if you try to divide by 0, you'd get a ZeroDivisionError.

# Handling a potential ZeroDivisionError exception

If you need to handle this in any way, use a try/except block to handle the error.

main.py
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)) # ๐Ÿ‘‰๏ธ 0

handle potential zerodivision error

The code for this article is available on GitHub

If a ZeroDivisionException error is raised in the try block, the except block runs.

# Getting the percentage increase/decrease between two numbers

The following function shows how to get the percentage increase/decrease between two numbers.

main.py
def get_percentage_increase(num_a, num_b): return ((num_a - num_b) / num_b) * 100 print(get_percentage_increase(60, 30)) # ๐Ÿ‘‰๏ธ 100.0 print(get_percentage_increase(40, 100)) # ๐Ÿ‘‰๏ธ -60.0

get percentage increase

The first example shows that the percentage increase from 60 to 30 is 100 %.

And the second example shows that the percentage increase from 40 to 100 is -60%.

If you always need to get a positive number, use the abs() function.

main.py
def get_percentage_increase(num_a, num_b): return abs((num_a - num_b) / num_b) * 100 print(get_percentage_increase(60, 30)) # ๐Ÿ‘‰๏ธ 100.0 print(get_percentage_increase(40, 100)) # ๐Ÿ‘‰๏ธ 60.0

get percentage decrease

The code for this article is available on GitHub

The abs() function returns the absolute value of a number. In other words, if the number is positive, the number is returned, and if the number is negative, the negation of the number is returned.

This way we are always guaranteed to get a positive number when calculating the difference in percentage between two numbers.

You might also need to handle the division by zero case.

main.py
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)) # ๐Ÿ‘‰๏ธ inf print(get_percentage_increase(60, 60)) # ๐Ÿ‘‰๏ธ 0.0 print(get_percentage_increase(60, 120)) # ๐Ÿ‘‰๏ธ 50.0

If we get a ZeroDivisionError error, we return Infinity, however, you can handle the error in any other way that suits your use case.

# Using the modulo % operator to calculate percentage

The third function in the code sample uses the modulo % operator.

main.py
def get_remainder(num_a, num_b): return num_a % num_b print(get_remainder(50, 15)) # ๐Ÿ‘‰๏ธ 5 print(get_remainder(50, 20)) # ๐Ÿ‘‰๏ธ 10

calculate percentage using modulo operator

The code for this article is available on GitHub

The modulo (%) operator returns the remainder from the division of the first value by the second.

main.py
print(10 % 2) # ๐Ÿ‘‰๏ธ 0 print(10 % 4) # ๐Ÿ‘‰๏ธ 2

If the value on the right-hand side is zero, the operator raises a ZeroDivisionError exception.

The left and right-hand side values may also be floating point numbers.

# Calculate a Percentage from User Input in Python

To calculate percentage from user input:

  1. Convert the input values to floats.
  2. Use the division / operator to divide one number by another.
  3. Multiply the quotient by 100 to get the percentage.
  4. The result shows what percent the first number is of the second.
main.py
def is_what_percent_of(num_a, num_b): return (num_a / num_b) * 100 num1 = float(input('Enter a number: ')) # ๐Ÿ‘‰๏ธ 25 num2 = float(input('Enter another number: ')) # ๐Ÿ‘‰๏ธ 75 result = is_what_percent_of(num1, num2) print(result) # ๐Ÿ‘‰๏ธ 33.33333333333333 print(round(result, 2)) # ๐Ÿ‘‰๏ธ 33.33

calculate percentage from user input

The code for this article is available on GitHub

Make sure to use the float() class to convert the input strings to floating-point numbers.

The input() function is guaranteed to return a string even if the user enters a number.

Use the round() function if you need to round the result to N decimal places.

The round function returns the number rounded to ndigits precision after the decimal point.

Note that if you try to divide by 0, you'd get a ZeroDivisionError.

# Calculate a Percentage Increase/Decrease from User Input in Python

If you need to get the percentage increase from one number to another, use the following function.

main.py
def get_percentage_increase(num_a, num_b): return ((num_a - num_b) / num_b) * 100 num1 = float(input('Enter a number: ')) # ๐Ÿ‘‰๏ธ 60 num2 = float(input('Enter another number: ')) # ๐Ÿ‘‰๏ธ 30 result = get_percentage_increase(num1, num2) print(result) # ๐Ÿ‘‰๏ธ 100.0 print(round(result, 2)) # ๐Ÿ‘‰๏ธ 100.0

calculate percentage increase from user input

The code for this article is available on GitHub

The example shows that the percentage increase from 60 to 30 is 100 %.

If you calculate the percentage increase from 40 to 100 you'd get -60% back.

If you always need to get a positive number, use the abs() function.

main.py
def get_percentage_increase(num_a, num_b): return abs((num_a - num_b) / num_b) * 100 print(get_percentage_increase(60, 30)) # ๐Ÿ‘‰๏ธ 100.0 print(get_percentage_increase(40, 100)) # ๐Ÿ‘‰๏ธ 60.0

The abs function returns the absolute value of a number.

In other words, if the number is positive, the number is returned, and if the number is negative, the negation of the number is returned.

# Formatting a Percentage value

You can use a formatted string literal if you need to format a percentage value.

main.py
# ๐Ÿ‘‡๏ธ if you need to format an input value to 1 or more decimal places user_input = input('Type a percentage, e.g. 10: ') result = f'{float(user_input) / 100:.1%}' print(result) # ๐Ÿ‘‰๏ธ 10.0%

format percentage

The code for this article is available on GitHub

The example uses a formatted string literal to format an input value to 1 or more decimal places.

main.py
user_input = input('Type a percentage, e.g. 10: ') result = f'{float(user_input) / 100:.1%}' print(result) # ๐Ÿ‘‰๏ธ 10.0% result = f'{float(user_input) / 100:.2%}' print(result) # ๐Ÿ‘‰๏ธ 10.00%
Formatted string literals (f-strings) let us include expressions inside of a string by prefixing the string with f.

Make sure to wrap expressions in curly braces - {expression}.

We are also able to use the format specification mini-language in expressions in f-strings.

main.py
my_float = 0.79 result_1 = f'{my_float:.1%}' print(result_1) # ๐Ÿ‘‰๏ธ 79.0% result_2 = f'{my_float:.2%}' print(result_2) # ๐Ÿ‘‰๏ธ 79.00%

The digit after the period determines how many decimal places the value should have.

The percent % sign after the digit is used to format the value as a percentage.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev