How to Calculate a Percentage in Python
There is no percentage operator in Python to calculate the percentage, but it is irrelevant to implement on your own.
Python Percentage
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.
quotient = 3 / 5 percent = quotient * 100 print(percent)
Output
60.0
That means its a 60%.
You can create a custom function in Python to calculate the percentage.
def percentage(part, whole): percentage = 100 * float(part)/float(whole) return str(percentage) + "%" print(percentage(3, 5))
Output
60.0%
You may want to add an if statement the whole is 0 return 0 since otherwise, this will throw an exception.
If you want the percentage about each other, then you need to use the following code.
def percent(x, y): if not x and not y: print("x = 0%\ny = 0%") elif x < 0 or y < 0: print("The inputs can't be negative!") else: final = 100 / (x + y) x *= final y *= final print('x = {}%\ny = {}%'.format(x, y)) percent(3, 6)
Output
x = 33.33333333333333% y = 66.66666666666666%
Python % sign(Modulo Operator)
The percent sign in Python is called modulo operator “%,” which returns the remainder after dividing the left-hand operand by the right-hand operand.
data = 3 info = 2 remainder = data % info print(remainder)
Output
1
The output will appear as a “1“. Here, the modulo operator “%” returns the remainder after dividing the two numbers.
The %s operator enables you to add value to a Python string. The %s signifies that you want to add string value into the string; it is also used to format numbers in a string.
That is it for finding percentages in the Python tutorial.
really helpful