How to calculate a percentage in Python

Learn how to calculate percentages in Python. This guide covers various methods, real-world examples, common errors, and debugging tips.

How to calculate a percentage in Python
Published on: 
Fri
Feb 6, 2026
Updated on: 
Sun
Apr 5, 2026
The Replit Team

To calculate a percentage in Python is a fundamental operation in data science and finance. Python makes this task simple with basic arithmetic operators like * and /, which ensures your code is readable.

In this article, we'll cover several techniques for these calculations. You'll get practical tips, see real-world applications, and learn to debug common errors, so you can confidently handle percentages in your projects.

Basic percentage calculation

value = 25
total = 80
percentage = (value / total) * 100
print(f"{value} is {percentage}% of {total}")--OUTPUT--25 is 31.25% of 80

The code translates the standard percentage formula—(value / total) * 100—directly into Python using basic arithmetic operators. Parentheses ensure the division operation happens first, which is essential for calculating the correct decimal ratio before converting it to a percentage.

This approach keeps your code intuitive and readable. The division value / total establishes the part-to-whole relationship, and multiplying by 100 simply scales that ratio into a percentage format. The final f-string then presents the output in a clear, human-readable sentence.

Formatting and displaying percentages

You can refine this output for greater clarity by controlling decimal precision, mastering f-string formatting, and easily converting between decimals and percentages.

Using the round() function for precision

sales = 85
target = 100
percentage = round((sales / target) * 100, 2)
print(f"Sales achieved: {percentage}% of target")--OUTPUT--Sales achieved: 85.0% of target

For cleaner results, Python’s built-in round() function lets you specify decimal precision. You simply pass the number to round and how many decimal places you need.

  • The code uses round(..., 2) to limit the percentage to two decimal places.
  • This ensures your output is tidy and easy to read, which is especially important in reports or user interfaces.

It’s a straightforward way to manage floating-point numbers without complex formatting tricks.

Creating percentage displays with f-strings

correct = 18
total_questions = 20
score_percentage = (correct / total_questions) * 100
print(f"Test score: {score_percentage:.1f}%")
print(f"Test score: {int(score_percentage)}%") # Without decimal places--OUTPUT--Test score: 90.0%
Test score: 90%

F-strings give you powerful formatting control directly within your string. This lets you manage how percentages appear without extra function calls. To master all the formatting options available, learn how to use f-string in Python.

  • Use a format specifier like :.1f to limit the output to a specific number of decimal places—in this case, one.
  • For a whole number, you can cast the value to an integer with int() inside the f-string to truncate the decimal portion.

Converting between decimals and percentages

decimal_value = 0.753
percentage = decimal_value * 100
print(f"Decimal {decimal_value} as percentage: {percentage}%")

percentage_value = 42.5
decimal = percentage_value / 100
print(f"Percentage {percentage_value}% as decimal: {decimal}")--OUTPUT--Decimal 0.753 as percentage: 75.3%
Percentage 42.5% as decimal: 0.425

Converting between decimals and percentages is a core data manipulation task. The logic is just simple arithmetic, which makes it easy to switch between formats as needed for calculations or display.

  • To turn a decimal like 0.753 into a percentage, you multiply it by 100.
  • To convert a percentage like 42.5 back to a decimal, you do the reverse and divide by 100.

Advanced percentage calculations

Now that you can handle basic percentages, you can move on to calculating percentage change and using libraries like pandas and numpy for more complex analysis.

Calculating percentage change

old_value = 200
new_value = 250
percent_increase = ((new_value - old_value) / old_value) * 100
print(f"Percentage increase: {percent_increase:.1f}%")

new_value = 150
percent_decrease = ((old_value - new_value) / old_value) * 100
print(f"Percentage decrease: {percent_decrease:.1f}%")--OUTPUT--Percentage increase: 25.0%
Percentage decrease: 25.0%

To find the percentage change, you measure the difference between a new and an old value relative to the starting point. This is crucial for tracking trends like sales growth or performance changes.

  • The formula ((new_value - old_value) / old_value) * 100 calculates the change.
  • The old_value is always the divisor because it’s the baseline you're measuring against.

This ensures you're calculating the change as a proportion of what it was originally, whether it's an increase or a decrease.

Using pandas for percentage calculations

import pandas as pd

df = pd.DataFrame({'sales': [100, 150, 200, 250]})
df['pct_of_total'] = df['sales'] / df['sales'].sum() * 100
df['pct_change'] = df['sales'].pct_change() * 100
print(df)--OUTPUT--sales pct_of_total pct_change
0 100 14.285714 NaN
1 150 21.428571 50.000000
2 200 28.571429 33.333333
3 250 35.714286 25.000000

When you're working with datasets, the pandas library simplifies percentage calculations. It lets you perform operations on entire columns at once, which is both fast and efficient. Before working with pandas operations, you'll need to know how to create a dataframe in Python. This makes Python particularly well-suited for AI coding with Python.

  • The pct_of_total column is created by dividing the sales column by its total sum. This shows each value's share of the whole.
  • For percentage change, the built-in pct_change() method does the heavy lifting. It automatically calculates the change from the previous row, which is why the first value is NaN.

Leveraging numpy for efficient percentage operations

import numpy as np

values = np.array([15, 30, 45, 60, 75])
total = np.sum(values)
percentages = np.round((values / total) * 100, 1)
cumulative_pct = np.cumsum(percentages)
print(f"Values: {values}\nPercentages: {percentages}\nCumulative %: {cumulative_pct}")--OUTPUT--Values: [15 30 45 60 75]
Percentages: [ 6.7 13.3 20. 26.7 33.3]
Cumulative %: [ 6.7 20. 40. 66.7 100. ]

For large datasets, numpy offers a significant performance boost by running calculations across entire arrays at once. This approach avoids slow, manual loops and keeps your code concise.

  • The code first calculates the percentage for each value in the numpy array with a single, vectorized operation.
  • It then uses np.cumsum() to efficiently compute a running total of these percentages, which is useful for tasks like building a Pareto chart.

Move faster with Replit

Replit is an AI-powered development platform that comes with all Python dependencies pre-installed, so you can skip setup and start coding instantly. This lets you move from learning individual techniques to building complete applications with Agent 4, which handles everything from writing code to deployment based on your description.

Instead of piecing together functions, you can describe the app you want to build and let Agent 4 take it from idea to working product:

  • A financial dashboard that calculates the percentage change in monthly spending and visualizes each category's share of the total budget.
  • A sales analytics tool that uses pandas to calculate period-over-period growth and identify top-performing products by their contribution to total revenue.
  • A statistical utility that processes a dataset with numpy to compute cumulative percentages for a Pareto analysis.

Simply describe your app, and Replit will write the code, test it, and fix issues automatically, all within your browser.

Common errors and challenges

When calculating percentages, you'll often encounter issues like division by zero, type errors, or unexpected NaN values, but they're all manageable.

  • Handling division by zero in percentage calculations
  • Fixing type errors in percentage inputs
  • Dealing with NaN values in percentage calculations

Handling division by zero in percentage calculations

Dividing by zero is a mathematical impossibility, and Python enforces this with a ZeroDivisionError. This error is common in percentage calculations when your 'total' value is zero, like trying to find a percentage of an empty inventory. The code below triggers it.

def calculate_percentage(value, total):
percentage = (value / total) * 100
return percentage

items_sold = 25
total_inventory = 0 # Zero inventory
success_rate = calculate_percentage(items_sold, total_inventory)
print(f"Sold {success_rate}% of inventory")

Since total_inventory is 0, the division (value / total) inside the calculate_percentage function fails, triggering the error. The code below shows how to guard against this.

def calculate_percentage(value, total):
if total == 0:
return 0 # or return a meaningful value for your use case
percentage = (value / total) * 100
return percentage

items_sold = 25
total_inventory = 0 # Zero inventory
success_rate = calculate_percentage(items_sold, total_inventory)
print(f"Sold {success_rate}% of inventory")

The solution is to add a conditional check before the division. This guard clause prevents the ZeroDivisionError by handling the edge case gracefully.

  • The if total == 0: statement intercepts a zero denominator.
  • Instead of crashing, the function returns a safe default like 0.

It’s a crucial safeguard when working with data that might be empty or uninitialized, like initial inventory counts, where a total can legitimately be zero.

Fixing type errors in percentage inputs

A TypeError is a common hurdle that occurs when you try to perform math on incompatible data types, like dividing a string by a number. This often happens with user input, since Python reads it as text by default. The following code triggers this error.

user_input = input("Enter percentage value: ")
decimal_value = user_input / 100 # Will cause TypeError
print(f"{user_input}% as a decimal is {decimal_value}")

The division operator / can't be used on the string value from input(). This mismatch between the operation and the data type is what triggers the TypeError. The following code shows how to prevent this.

user_input = input("Enter percentage value: ")
decimal_value = float(user_input) / 100
print(f"{user_input}% as a decimal is {decimal_value}")

The solution is to explicitly convert the input string to a number before the calculation. By wrapping the result of input() with the float() function, you transform the text into a floating-point number that supports mathematical operations. This simple type conversion prevents the TypeError entirely.

  • You'll find this technique essential whenever you're working with data from external sources, like user input or text files, which Python often reads as strings by default.

Dealing with NaN values in percentage calculations

In data analysis, you'll often encounter NaN (Not a Number) values, which act as placeholders for missing information. When performing calculations, these NaN values can propagate, leading to unexpected gaps in your results. The following code demonstrates this issue.

import pandas as pd

data = {'values': [10, 20, None, 40, 50]}
df = pd.DataFrame(data)
df['percentage'] = (df['values'] / df['values'].sum()) * 100
print(df)

The None value in the values column becomes NaN. Any arithmetic operation involving NaN results in NaN, which is why the percentage for that row is also missing. Check out the code below for a simple fix.

import pandas as pd

data = {'values': [10, 20, None, 40, 50]}
df = pd.DataFrame(data)
df['percentage'] = (df['values'] / df['values'].sum(skipna=True)) * 100
print(df)

The fix is to tell the sum() function to ignore missing values when calculating the total. This ensures that any NaN entries don't disrupt the entire operation, which is a common issue with real-world data where information is often incomplete.

  • By setting skipna=True, pandas calculates the sum using only the valid numbers.
  • The row with the original NaN value still results in a NaN percentage, but the other calculations now work correctly.

Real-world applications

Now that you can handle common errors, you can apply these percentage skills to practical scenarios like calculating tips or analyzing data outliers.

Calculating restaurant tips with percentages

You can apply the same percentage logic to practical, everyday tasks like calculating a tip on a restaurant bill.

bill_amount = 85.50
tip_percentage = 18
tip_amount = bill_amount * (tip_percentage / 100)
total_amount = bill_amount + tip_amount
print(f"Bill: ${bill_amount}, Tip ({tip_percentage}%): ${tip_amount:.2f}, Total: ${total_amount:.2f}")

This code calculates the tip_amount by first converting the tip_percentage into its decimal form. It does this by dividing the percentage by 100 before multiplying it with the bill_amount. This is a direct and common way to find a percentage of a number.

  • The final total_amount is a simple sum of the original bill and the calculated tip.
  • The print() function then uses an f-string with the :.2f format specifier to display the monetary values correctly with two decimal places.

Analyzing data outliers with percentage thresholds

Percentages are also useful for setting dynamic thresholds to flag outliers in a dataset, such as values that are a certain percentage above or below the mean. When working with real datasets for percentage analysis, you'll often need to read a CSV file in Python first.

import numpy as np

data = np.array([23, 45, 67, 32, 56, 78, 90, 12, 34, 56])
mean = np.mean(data)
above_threshold = data[data > (mean * 1.2)] # Values 20% above mean
percent_above = (len(above_threshold) / len(data)) * 100

print(f"Mean: {mean:.2f}")
print(f"Values 20% above mean: {above_threshold}")
print(f"Percentage of values above threshold: {percent_above:.1f}%")

This code uses numpy to filter data based on a dynamic threshold. It first calculates the dataset's average with np.mean() and sets a threshold at 120% of that value, or 20% above the mean.

  • It then leverages boolean indexing—a powerful numpy feature where you filter an array based on a condition—to select only the values exceeding this threshold.
  • Finally, it determines what percentage of the original data these selected values represent by comparing the lengths of the filtered and original arrays.

Get started with Replit

Turn your knowledge into a real tool with Replit Agent. Just describe what you want: “Build a tip calculator app” or “Create a script that calculates each product’s share of total sales from a CSV.”

Replit Agent will write the code, test for errors, and deploy your application for you. Start building with Replit.

Build your first app today

Describe what you want to build, and Replit Agent writes the code, handles the infrastructure, and ships it live. Go from idea to real product, all in your browser.

Build your first app today

Describe what you want to build, and Replit Agent writes the code, handles the infrastructure, and ships it live. Go from idea to real product, all in your browser.