Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 842
nim6us Avatar asked May 13 '11 21:05

nim6us


People also ask

How do you calculate percentages in Python?

To calculate a percentage in Python, use the division operator (/) to get the quotient from two numbers and then multiply this quotient by 100 using the multiplication operator (*) to get the percentage. This is a simple equation in mathematics to get the percentage.

What operation do you use to find the percentage?

You then express the quantity in question as a fraction of the total, and to make the number more useful, you do two more simple operations. The first is to divide the denominator of the fraction into the numerator to get a decimal fraction, which is one with a base of 10. You then multiply by 100 to get a percentage.


2 Answers

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 
like image 56
Brian Campbell Avatar answered Sep 22 '22 22:09

Brian Campbell


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.

like image 44
Rafe Kettler Avatar answered Sep 21 '22 22:09

Rafe Kettler