# Is there an operator to calculate percentage in Python?

## Is there an operator to calculate percentage in Python?

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 Smiths answer), you would write:

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

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.

# 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
``````