How to Calculate a Percentage in Python

To get a percentage of two numbers in Python, divide them using the division operator (/) then multiply the result by 100 using the Python multiplication operator (*).

 

To demonstrate this, let's get the percentage of 3 out of 9 using Python.

 

percent = 3 / 9 * 100

print(percent)
33.33333333333333

 

Python Percentage Function

If you need to get percentages many times in your program, it may be worth creating a small helper function.

 

def getPercent(first, second, integer = False):
   percent = first / second * 100
   
   if integer:
       return int(percent)
   return percent

print(getPercent(3, 9))
33.33333333333333

 

With the above function, to get an integer back pass True as the third argument.

 

def getPercent(first, second, integer = False):
   percent = first / second * 100
   
   if integer:
       return int(percent)
   return percent

print(getPercent(3, 9, True))
33