Calculate Percentage in Python
In this post, you will learn how to calculate percent in different ways using the Python programming language. Such a type of logical question is generally asked in programming interviews or examinations.
To calculate the percent of a number, divide the number by the whole and multiply it by 100. Here, we have used two different ways to calculate the percentage.
Python Calculate Percentage using Division and Multiplication
To calculate the percentage, we use the division operator (/) to get the quotient from two numbers and multiply this quotient by 100 using the multiplication operator (*) to get the percentage. Suppose we want to get a percentage of 4 out of 19. The following Python program calculates the percentage.
percent = 4 / 19 * 100
print("Percentage of 4 out of 19: ",percent)
Output of the above code:
Percentage of 4 out of 19: 21.052631578947366
Python Calculate Percentage using Function
In the given Python program, we have defined a small function calPercent() to calculate the percentage.
def calPercent(x, y, integer = False):
percent = x / y * 100
if integer:
return int(percent)
return percent
print("Percentage: ",calPercent(33, 200))
Output of the above code:
Percentage: 16.5
Python Calculate Percentage using user input and user-defined function
In the given Python program, we have taken two inputs from the user using the input() function and stored them in two variables, x and y respectively, and then calculated the percentage.
def calPercent(x, y, integer = False):
percent = x / y * 100
if integer:
return int(percent)
return percent
# User Input
a=int(input("Enter the first number: "))
b=int(input("Enter the second number: "))
print("Percentage: ",calPercent(a,b))
Output of the above code:
Enter the first number: 67
Enter the second number: 150
Percentage: 44.666666666666664
Related Articles
Python convert list to numpy arrayHow to shuffle a list in Python
Print hollow diamond pattern in Python
Python program to multiply two matrices
Python Numpy Array Shape
Python Pandas Dataframe to CSV
Inverse of a matrix in Python
Remove element from list Python
Python iterate list with index
Python program to sum all the numbers in a list
Python print without newline
2d arrays in Python
Python add list to list
Python convert xml to dict
Python dict inside list
Multiply all elements in list Python
Python heap implementation using heapq module
numpy dot product
Python convert dict to xml
Python weather api
Python raise keyword