2 ways to calculate a percentage in python:
- Basic Percentage Calculation
- Calculating a Percentage of List
Method 1: Basic Percentage Calculation
You can use the division operator to divide one number by another, and then multiply the result by 100.
Using the standard formula: (Part / Whole) * 100.
Example 1
part = 3
whole = 5
percentage = (part / whole) * 100
print(percentage)
Output
60.0
That means its a 60%.
Example 2 : Using a custom function
def calculate_percentage(part, whole):
return str((part / whole) * 100) + "%"
percentage = calculate_percentage(3, 5)
print(percentage)
Output
60.0%
Example 3 : Handling a ZeroDivisionError exception
If the whole is 0, it will throw an exception. So, we can handle this through a try-except block.
def calculate_percentage(part, whole):
try:
return (part / whole) * 100
except ZeroDivisionError:
return 0
percentage = calculate_percentage(3, 0)
print(percentage)
Output
0
Method 2: Calculating a Percentage of List
Here are three ways to calculate a percentage of a list:
- Using list comprehension and len()
- Using filter(), lambda, and len()
- Using list(), map() and find()
Method 2.1: Using list comprehension and len()
You can calculate the number of even elements with list comprehension and len(), then divide by the total number of elements and multiply by 100.
Example
num_list = [1, 2, 3, 4, 5]
#Using list comprehension to filter the list and calculate the percentage of even numbers
percent = (len([a for a in num_list if a % 2 == 0]) / len(num_list)) * 100
#Percentage of number of even elements in the list
print(str(percent))
Output
40.0
Method 2.2: Using filter(), lambda, and len()
The filter function combined with a lambda function is used to create a new list containing only the even numbers.
Example
num_list = [1, 2, 3, 4, 5]
# Filtering even numbers from num_list
even_numbers = list(filter(lambda x: x % 2 == 0, num_list))
# Calculating and printing the percentage of even numbers
percent = (len(even_numbers) / len(num_list)) * 100
print(percent)
Output
Percentage of number of even elements in the list : 40.0
Method 2.3: Using list(), map() and find()
Example
num_list = [0, 1, 2, 3, 0, 4, 5]
# Printing the original list
print("The original list is : " + str(num_list))
# Convert the numbers to strings and filter for non-zero elements
res = []
x = list(map(str, num_list))
for i in x:
if i != "0": # Correct condition to check for non-zero elements
res.append(int(i))
# Calculate the percentage of non-zero elements
percentage = (len(res) * 100) / len(num_list)
# Printing the result
print(str(percentage))
Output
71.42857142857143
Yathartha
really helpful
duffer
i dont’ know