How to Calculate a Percentage in Python

Python, a versatile and robust programming language, offers many methods to perform mathematical operations, including calculating percentages. This article aims to provide an in-depth guide on how to calculate percentages in Python, with a focus on simplicity and clarity. We will explore various techniques, enriched with examples, to ensure a comprehensive understanding of the topic.

The Basics: Calculating Percentages in Python

Calculating a percentage in Python is straightforward. The process involves dividing one number by another and multiplying the result by 100. This operation gives us the percentage of the first number of the second.

Let’s illustrate this with a function:

def calculate_percentage(num1, num2):
    return (num1 / num2) * 100

For instance, if we want to find out what percentage 25 is of 50, we can use the function like this:

print(calculate_percentage(25, 50))  # Output: 50.0

This example shows that 25 is 50% of 50. Similarly, you can replace the numbers with any two numbers of your choice to calculate the percentage.

Precision Matters: Rounding to Specific Decimal Places

When dealing with percentages, it’s common to round the results to a specific number of decimal places. Python’s built-in round() function is perfect for this task. It takes two parameters: the number to be rounded and the number of decimal places to round to.

print(round(calculate_percentage(33, 65), 2))  # Output: 50.77

In this example, the round() function rounds the result of the percentage calculation to two decimal places, providing a more precise and readable output.

Error Handling: Dealing with ZeroDivisionError Exceptions

In Python, attempting to divide by zero raises a ZeroDivisionError. To handle this, we can use a try/except block. Here’s how we can modify our calculate_percentage() function to return 0 when a ZeroDivisionError occurs:

def calculate_percentage(num1, num2):
        return (num1 / num2) * 100
    except ZeroDivisionError:
        return 0

This modification ensures that our function handles the edge case of division by zero, enhancing its robustness.

Understanding Change: Calculating Percentage Increase or Decrease

Python also enables us to calculate the percentage increase or decrease between two numbers. The following function demonstrates how to achieve this:

def calculate_percentage_change(num1, num2):
    return ((num1 - num2) / num2) * 100

This function subtracts the second number from the first, divides the result by the second number, and multiplies by 100 to get the percentage change. If the result is positive, it indicates a percentage increase; if negative, a percentage decrease.

User Interaction: Calculating Percentages with User Input

Python’s input() function allows us to accept user input. However, it always returns a string, so we need to convert the input to a float before performing any calculations. Here’s how we can modify our calculate_percentage() function to accept user input:

def calculate_percentage():
    num1 = float(input('Enter the first number: '))
    num2 = float(input('Enter the second number: '))
    return (num1 / num2) * 100

This modification allows our function to interact with users, making it more versatile and practical.

Presentation Matters: Formatting Percentage Values

Python’s f-strings provide a concise and convenient way to embed expressions inside string literals for formatting. We can use them to format our percentage values to a specific number of decimal places:

percentage = calculate_percentage(25, 50)
formatted_percentage = f'{percentage:.2f}%'
print(formatted_percentage)  # Output: 50.00%

In this example, the :.2f inside the f-string rounds the percentage to two decimal places, and the % symbol appends a percentage sign to the end of the string.


In conclusion, this article has provided a comprehensive guide on how to calculate percentages in Python. We’ve explored various methods, including basic percentage calculation, rounding to specific decimal places, handling ZeroDivisionError exceptions, and calculating percentage changes. We’ve also discussed how to accept user input for these calculations and format the results for better readability.

As a final recommendation, it’s crucial to remember that Python’s power lies in its simplicity and flexibility. You can handle various mathematical operations and data analysis tasks by understanding and applying these techniques. This knowledge enhances your Python programming skills and equips you with the tools to solve complex problems efficiently. Always remember practice is vital to mastering these concepts. Happy coding!

Share to...