Python find percentage of value

Brian's answer (a custom function) is the correct and simplest thing to do in general.

But if you really wanted to define a numeric type with a (non-standard) '%' operator, like desk calculators do, so that 'X % Y' means X * Y / 100.0, then from Python 2.6 onwards you can redefine the mod() operator:

import numbers

class MyNumberClasswithPct(numbers.Real):
    def __mod__(self,other):
        """Override the builtin % to give X * Y / 100.0 """
        return (self * other)/ 100.0
    # Gotta define the other 21 numeric methods...
    def __mul__(self,other):
        return self * other # ... which should invoke other.__rmul__(self)
    #...

This could be dangerous if you ever use the '%' operator across a mixture of MyNumberClasswithPct with ordinary integers or floats.

What's also tedious about this code is you also have to define all the 21 other methods of an Integral or Real, to avoid the following annoying and obscure TypeError when you instantiate it

("Can't instantiate abstract class MyNumberClasswithPct with abstract methods __abs__,  __add__, __div__, __eq__, __float__, __floordiv__, __le__, __lt__, __mul__,  __neg__, __pos__, __pow__, __radd__, __rdiv__, __rfloordiv__, __rmod__, __rmul__,  __rpow__, __rtruediv__, __truediv__, __trunc__")

Calculate percentage in Python #

To calculate 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.

Copied!

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 # -------------------------------------------------- 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 # -------------------------------------------------- def get_remainder(num_a, num_b): return num_a % num_b print(get_remainder(50, 15)) # 👉️ 5 print(get_remainder(50, 20)) # 👉️ 10

The first 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.

Copied!

print((25 / 50) * 100) # 👉️ 50.0

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
number the number to round to ndigits precision after the decimal
ndigits the number of digits after the decimal the number should have after the operation (optional)

Copied!

print(round((33 / 65) * 100, 2)) # 👉️ 50.77

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.

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

Copied!

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

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

Copied!

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

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.

Copied!

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.

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.

Copied!

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.

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

Copied!

def get_remainder(num_a, num_b): return num_a % num_b print(get_remainder(50, 15)) # 👉️ 5 print(get_remainder(50, 20)) # 👉️ 10

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

Copied!

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.

How do you find a percentage of a value?

Convert the problem to an equation using the percentage formula: P% * X = Y..
P is 10%, X is 150, so the equation is 10% * 150 = Y..
Convert 10% to a decimal by removing the percent sign and dividing by 100: 10/100 = 0.10..

How do you calculate the percentage of each element in a list Python?

In this, we construct positive elements list using list comprehension and then compute the length of lists using len(), both lengths are divided and multiplied by 100 to get percentage count.

Is there a percentage function in Python?

In python the “%” has two different uses. First, when used in a math problem like those above, it is used to represent modulus. The modulus of a number is the remainder left when you divide. 4 mod 5 = 4 (you can divide 5 into 4 zero times with a remainder of 4).

How do I extract a percentage from a number?

How to calculate a percentage.
Determine the total amount of what you want to find a percentage. For example, if you want to calculate the percentage of days it rained in a month, you would use the number of days in that month as the total amount. ... .
Divide the number to determine the percentage. ... .
Multiply the value by 100..