This comprehensive guide will explore the various approaches we can use to calculate a percentage in Python for different use cases. The concept of percentages is a way to frame a fraction out of 100, describing a part of the whole. In other words, it’s like splitting something into 100 equal parts and calculating how many parts you have from each. As an example, if you own 33 out of 66 pencils, it means you own 50%. Percentage calculations are a fundamental mathematical concept that has applications in various real-world situations. Moreover, Percentage computing is beneficial in various fields and scenarios where you want to express a portion of a whole as a percentage. Additionally, comparing things and figuring out proportions is super easy with percentages.
Why do Percentages Matter in Interpreting Data?
For decision-making, analysis, and communication in a wide variety of domains, such as engineering (efficiency & error rate), elections, and determining the goals of running a social media marketing, education, and data analytics campaign, it provides a standardized scale for expressing relationships between parts and wholes, which can be vital. The percentage tool uses in other domains to gain insights into desired outcomes.
If you want to learn more about Python Programming, visit Python Programming Tutorials.
METHODS TO calculate percentages in Python
Computing a percentage in Python is relatively straightforward. Here’s the standard practice followed to calculate a percentage in Python :
Where:
- The value you want to find is the percentage of.
- The total value.
percentage = (Value %age of / total value) * 100
This command line calculates the percentage in Python by dividing part by whole and then multiplying by 100 to convert the fraction to a percentage.
However, you can memorize this syntax by the following percentage calculator trick:
<em>part</em> ፥ whole = %፥100
Or
Is፥of = %፥100
To format the result as a percentage in Python, we use the “%” symbol. This symbol illustrates Python to format the number as a percentage. In the example, you’re calculating 0.25 times 100 to get the percentage value and then printing it. The result displays as 25.0 %.
This approach works if you have a direct value that you want to represent as a percentage.
computing_percentage = 0.25 * 100
print(computing_percentage, '%')
25.0 %
If you have a scenario where you want to calculate a percentage from two values, like calculating the percentage of students who passed an exam or the growth rate of a plant, then use the other approaches that we are going to discuss in this article.
Using a more concise approach, this tutorial article describes several methods for calculating a percentage in Python with examples and real-world scenarios.
In this section, we will discuss the following methods in detail:
- Computing A Percentage for complex scenarios
- Defining a Function to Calculate Percentages
- Calculating Percentages from User Input
- Calculating an average percentage using def and split() function
- Exception Handling while Calculating Percentages
- Using the Round Function for Calculating Percentages
- Using the Formatting Specifier to Format a Percentage
- Using F-String to Format a Percentage
1) Calculate A Percentage for complex scenarios in Python
You can calculate a percentage in Python easily by dividing fractions by 100. To calculate a percentage of a number, we divide the number by the whole and multiply ‘*’ by 100.
Let’s consider a business scenario where we want to calculate the profit margin percentage. Profit margin is a key financial indicator that expresses the profitability of a business by measuring the percentage of profit generated from its revenue.
Here’s how you can calculate the profit margin percentage in Python:
# Input values
revenue = 100000 # Total revenue
expenses = 50000 # Total expenses
# Calculate the profit margin
profit_margin = revenue - expenses
print(type(profit_margin))
# computing the profit margin percentage
profit_margin_percentage = (profit_margin / revenue) * 100
print(type(profit_margin_percentage))
# the result
percentage_output = "The profit margin is: {:.2f}%".format(profit_margin_percentage)
print(percentage_output, type(percentage_output))
Output:
<class 'int'>
<class 'float'>
The profit margin is: 50.00% <class 'str'>
In this example, we calculate the profit margin percentage by the difference between revenue and expenses. Here computing the percentage by taking them as fractional values (part/whole) multiplied by 100. The part value in the percentage formula is first to calculate the difference between the total revenue and expense. Then, divide the difference by the whole value (i.e. total revenue) to extract the percentage.
The format() method is used to format the percentage value with two decimal places. The format() function converts the percentage integer value to string data type and then to two decimal places.
2) Defining a Function to Calculate Percentages
We can also define a function that can calculate a percentage and call this function multiple times in our code. The user-defined function helps us to calculate the percentage concisely within a few statements. When exploring the user-defined function, you have two options either use the return statement explicitly to return the output within the explicit return function or implicitly return the output.
This example, however, shows how the percentage of pothos growth is easily and concisely calculated over four weeks in botanical research. However, the developers constructed a user-friendly application to get insights into the growth rate of the Pothos plant. A developer can encapsulate the functionality within a user-defined function and create a user-friendly interface using Python libraries. Since the following piece of code computes the percentage is quite helpful in this scenario.
The function is invoked with its argumentative values (10,22). And the results are saved in the object variable ‘pothos_growth_rate’. The print function is the contextual representation of the defined function results.
def calc_percentage_growth(initial_size, final_size):
growth_rate_percentage = ((final_size - initial_size) / initial_size) * 100
return growth_rate_percentage
# Initial size & Final size in centimeters
pothos_growth_rate = calc_percentage_growth(10, 22)
print("Pothos plant growth rate =", pothos_growth_rate, "% over 4 weeks",type(pothos_growth_rate))
Output:
Pothos plant growth rate = 120.0 % over 4 weeks <class 'float'>
3) Calculating Percentage through Getting Input from the User
Let’s consider a situation where you want to calculate the percentage of students who passed an exam out of the total number of students who took the exam. The user-defined function uses to calculate the passing percentage. To format the result as a percentage in Python, use the “%” symbol. The formula is defined within the function context. Every time a program calls a function, within the program, the return statement returns the operation explicitly that is passed to it. The output will be the percentage of students who passed the exam out of the total number of students who took the exam.
def calc_percentage(part, whole):
return (part / whole) * 100
# Input the number of students who passed and the total number of students
students_passed = float(input('Enter the number of students who passed: '))
total_students = float(input('Enter the total number of students: '))
passing_percentage = calc_percentage(students_passed, total_students)
print('Passing Percentage =', passing_percentage, '%')
Output:
Enter the number of students who passed: 23
Enter the total number of students: 25
Passing Percentage = 92.0 %
The ‘input()’ function uses to get the user input for both part and whole. The ‘float()’ function converts the user input into floating-point numbers (decimal numbers) for greater accuracy.
Calculating an average percentage using def and split() function
Let’s extract the average percentage in another example and take the input from the user. The average percentage calculates in Python using the define function with a return statement. The return statement returns the calculated average percentage from the function by calculating the percentage by dividing part by whole and then multiplying by 100 to convert the fraction to a percentage.
The split() function splits the input string into individual score values, converts each score to a floating-point number, and stores them in a list using a list comprehension for…in structure.
The print() function uses an f-string format specifier to print the average percentage with two decimal places and use % symbol for it.
def calculate_average_percentage(scores, total_possible_score):
total_scores = sum(scores)
average_percentage = (total_scores / (len(scores) * total_possible_score)) * 100
return average_percentage
# Get user input for test scores
scores_str = input("Enter the test scores separated by spaces: ")
scores = [float(score) for score in scores_str.split()]
# Get user input for total possible score
total_possible_score = float(input("Enter the total possible score: "))
# Calculate the average percentage
average_percentage = calculate_average_percentage(scores, total_possible_score)
print(f"The average percentage is: {average_percentage:.2f}%")
Enter the test scores separated by spaces: 23.45
Enter the total possible score: 67.79
The average percentage is: 34.59%
In the above example, the function is defined using the def keyword that calculates the average percentage of a list of test scores. It then takes user input for the test scores and the total possible score performs the calculation and prints the average percentage with two decimal places.
4) Exception Handling while Calculating Percentages in Python
For the process of calculating a percentage in Python, we can also come across a scenario where a number is divided by zero, causing a zero division error. To tackle the situation where the program may crash while computing the mathematical problems which is undefined, we can use a try-except block in Python.
Let’s consider a scenario in which the objective is to calculate the accurate percentage of clicks per impression for a social media page or website page. In the following example, the input is taken from the user using the inbuilt Python input() function. However, within the defined function, the percentage is calculated by multiplying 100 with the fractional value.
If the user input 0 against impression, the ctr will return 0 (as anything divided by zero is mathematically undefined). And the try-except block will execute the ZeroDivisionError body and return 0 after calculating the percentage. If the operation inside the try block encounters an error, the code inside the except block executes instead.
def calc_click_through_rate(clicks, impressions):
try:
ctr = (clicks / impressions) * 100
return ctr
except ZeroDivisionError:
return 0
# Get user input for clicks and impressions
clicks = float(input('Enter the number of clicks: '))
impressions = float(input('Enter the total number of impressions: '))
# Calculate the click-through rate
ctr = calc_click_through_rate(clicks, impressions)
print('Click-Through Rate =', ctr, '%')
Output:
Enter the number of clicks: 45
Enter the total number of impressions: 67
Click-Through Rate = 67.16417910447761 %
In the code above, we have included a try-except block inside the user-defined def function. This block uses to handle the possibility of a ‘ZeroDivisionError’ when the whole value is equal to zero. If the division by zero occurs, the except block executes then, and the function returns ‘0’.
5) Using the Round() Function To calculate a percentage in Python
While calculating percentages, we might need to round the percentage value to a specific number of decimal places. To accomplish this we can use the ‘round()’ function.
Calculating a percentage using a round() function is a concise and straightforward approach. The round() function rounds the output of the percentage to two decimal places. However, in the following example, the inventory system is tracking the gardening shop. The percentage computation plays a great impact on sales tracking.
In the following example, the sold inventory is divided by the available plant’s inventory, then multiplied by 100 in the defined function return statement. However, the return statement returns the computed percentage and returns the results up to 2 decimal places using the round() function.
def calc_percentage_sold(sold_plants, total_available_plants):
return round((sold_plants / total_available_plants) * 100, 2)
#user input sold plants by total available plants
sold_plants = float(input('Enter the number of sold plants: '))
total_available_plants = float(input('Enter the total number of available plants: '))
# Calculate the percentage of sold plants
percentage_sold = calc_percentage_sold(sold_plants, total_available_plants)
print('Percentage of Sold Plants =', percentage_sold, '%')
Output:
Enter the number of sold plants: 24
Enter the total number of available plants: 30
Percentage of Sold Plants = 80.0 %
In the example above, the ‘round()’ function uses inside the ‘calc_percentage_sold()’ function. The function explicitly returns the output by computing the operation with the return statement, the return statement expression calculates the percentage and returns the number of decimal places we need to round to, in this case, ‘2’.
6) Using the Formatting Specifier to Format a Percentage
We can also format the percentage value using the ‘str.format()’ function. Let’s consider the scenario of the airport ticket tracking system to calculate the percentage of passengers who booked business class tickets out of the total number of passengers. use the round() function and map() and the split() function to handle input.
Comma-separated ‘,’ input data is taken from the user who booked business class, from the total number of passengers. However, to convert these two values to floats, we use the map() and split() functions. The defined function calculates the percentage of booked business class passengers from the total passengers.
The output illustrates the print () command restricted to two decimal places using the format () method.
def calc_percentage(part, whole):
return (part / whole) * 100
#user input booked business class passengers and total passengers
# input number should be separated by a commas
input_str = input('Enter the number of booked business class passengers and total passengers: ')
booked_business_class, total_passengers = map(float, input_str.split(sep=','))
# Calculate the percentage of booked business class passengers
percentage_business_class = calc_percentage(booked_business_class, total_passengers)
# output with two decimal places
print('Percentage of Booked Business Class Passengers = {:.2f}%'.format(percentage_business_class))
Output:
Enter the number of booked business class passengers and total passengers: 33, 66
Percentage of Booked Business Class Passengers = 50.00%
Here, we have used the ‘.format()’ method to display the percentage value. The format specifier ‘{:.2f}‘ inside the string indicates that the percentage value displays with two decimal places. The ‘%’ character represents a percentage. When using ‘.format()’, the calculated percentage converts into the string with proper formatting.
Using formatted string literal to format the calculated Percentage
Another improved way to format our result is by using Python’s ‘f-string’ (formatted string literal) approach available in Python 3.6 and above.
The percentage is calculated and formats using the formatted string literal in Python to evaluate the reliability of the courier service’s delivery operations by tracking the percentage of successful rate of shipped and delivered packages.
In this example, you input the number of successfully delivered packages and the total number of packages shipped by the courier service. The def function calculates the percentage of delivered packages based on the user inputs using a return statement. When the function invokes these two parameters and the output returns by the return statement, then save into an object variable. The percentage formats up to two decimal places using the % symbol and the {} curly braces. Within the braces {}, the ‘:.2f’ controls the output of the percentage to 2 decimal places.
However, the result displays two decimal places using an f-string.
def calc_percentage(part, whole):
return (part / whole) * 100
# User input information for delivered packages and total shipped packages
delivered_packages = float(input('Enter the number of delivered packages: '))
total_shipped_packages = float(input('Enter the total number of shipped packages: '))
# Calculate the percentage of successfully delivered packages
percentage_delivered = calc_percentage(delivered_packages, total_shipped_packages)
# output set to two decimal places
print(f'Percentage of Successfully Delivered Packages = {percentage_delivered:.2f}%')
Output:
Enter the number of delivered packages: 5
Enter the total number of shipped packages: 6
Percentage of Successfully Delivered Packages = 83.33%
In the code above, we use the ‘{:.2f}’ expression inside the f-string, which illustrates the percentage value in two decimal places. The ‘%’ character includes to indicate that the value is a percentage.
Conclusion
As a result of this tutorial, we have explored how to calculate the percentage using the def function and % symbol. This approach enables you to calculate the percentage of any single number using the “%” character in Python, and if you have multiple numbers you calculate their percentage using the def keyword with or without a return statement. The try-except block method uses to find the percentage for more complex scenarios where the try-except block helps ensure that the calculation doesn’t crash the program. To learn more about how to calculate percentages in Python, check out the examples above and the approach outline. Exploring the percentage techniques and modifying the above example codes according to your scenarios!