nim6us
nim6us

Reputation: 847

Is there an operator to calculate percentage in Python?

I've recently learned that the " % " sign is used to calculate the remainder of an integer in Python. However I was unable to determine if there's another operator or method to calculate percent in Python.

Like with " / " which will give you the quotient, if you just use a float for one of the integers, it will actually give you the answer like traditional division. So is there a method to work out percentage?

Upvotes: 81

Views: 413806

Answers (8)

Omar Essam El-Din
Omar Essam El-Din

Reputation: 1873

Just use this

score_in_percentage = round( score *100 , 2 )
print(f' {score_in_percentage}% ') #50%

Upvotes: 0

Shunya
Shunya

Reputation: 2429

I have found that the most useful case for me is to compute the calculations as ratios and then printing the results formatting them as percentages thanks to Python formatting options:

result = 1.0/2.0            # result is 0.5
print(f'{result:.0%}')      # prints "50%"

Upvotes: 3

paivatulio
paivatulio

Reputation: 316

def percent(part, whole):
    try:
        return 100 * float(part) / float(whole)
    except ZeroDivisionError:
        return 0

Upvotes: 0

PythonProgrammi
PythonProgrammi

Reputation: 23443

use of %

def percent(expression="1000*12%") -> float:
    if "%" in expression:
        expression = expression.replace("%","")
        a, b = expression.split("*")
        a, b = float(a), float(b)
    return a*b/100

>>> percent("1500*20%")
300.0

Another way

p = lambda x : x/100
p20 = p(20)

>>> 150*p20
30.0

Upvotes: 10

Brian Campbell
Brian Campbell

Reputation: 332866

You could just divide your two numbers and multiply by 100. Note that this will throw an error if "whole" is 0, as asking what percentage of 0 a number is does not make sense:

def percentage(part, whole):
  return 100 * float(part)/float(whole)

Or with a % at the end:

 def percentage(part, whole):
  Percentage = 100 * float(part)/float(whole)
  return str(Percentage) + “%”

Or if the question you wanted it to answer was "what is 5% of 20", rather than "what percentage is 5 of 20" (a different interpretation of the question inspired by Carl Smith's answer), you would write:

def percentage(percent, whole):
  return (percent * whole) / 100.0

Upvotes: 195

ВелоКастръ
ВелоКастръ

Reputation: 4453

Very quickly and sortly-code implementation by using the lambda operator.

In [17]: percent = lambda part, whole:float(whole) / 100 * float(part)
In [18]: percent(5,400)
Out[18]: 20.0
In [19]: percent(5,435)
Out[19]: 21.75

Upvotes: 0

smci
smci

Reputation: 33950

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__")

Upvotes: 5

Rafe Kettler
Rafe Kettler

Reputation: 76955

There is no such operator in Python, but it is trivial to implement on your own. In practice in computing, percentages are not nearly as useful as a modulo, so no language that I can think of implements one.

Upvotes: 46

Related Questions