How to Calculate Percentage in Python. Calculating percentages is a fundamental mathematical operation, frequently used in various fields such as finance, data analysis, and general statistics. With its simplicity and flexibility, Python is an excellent tool for performing these calculations. In this article, we will explore different ways to calculate percentages using Python, providing clear examples for practical understanding.
Table of Contents
Basic Percentage Calculation in Python
Let’s start with the simplest case: Calculating what percent a part is of a whole. This is useful in situations like what percentage of a class passed an exam or what fraction of a budget has been spent.
Example: Calculating the pass percentage of students–
def calculate_percentage(part,whole):
percentage = (part/whole)*100
return percentage
student_passed =67
total_student =110
pass_percentage = calculate_percentage(student_passed,total_student)
print(f"The pass percenatge is {pass_percentage:.2f}%")
In the above Python code, the function takes two arguments (part and whole), calculates the percentage, and returns it. The '.2f'
in the print
function for making the percentage to two decimal places.
Calculating Percentage Increase or Decrease in Python
To determine how much a value has increased or decreased in percentage terms from an original value, use the following formula-
Percentage Change = ((New Value – Original Value) / Original Value)*100
Example: Calculate Salary Increase
def calculate_percentage_change(original,new):
change = ((new-original)/original)*100
return change
original_salary = 30000
new_salary = 34000
percentage_change = calculate_percentage_change(original_salary,new_salary)
print(f"The percenatge change is {percentage_change:.2f}%")
The function calculates the percentage change in the above Python code, which can be either positive (percentage increase) or negative (percentage decrease).
Calculating percentages in Python is straightforward thanks to its powerful arithmetic capabilities. Whether it is determining what fraction of a total a particular number represents, or calculating percentage increase or decrease, Python provides an efficient and clear approach.
Happy Coding & Learning
2 thoughts on “How to Calculate Percentage in Python”