This time we will create a class Percent to calculate percentage and we will create a new method to do it, but we will also use the calculate_x method of the class Prop of the module proportion we made in the last post.
A percentage, in fact, is a proportion in which one of the ratios has a base of 100 like 20%, 30% etc. So why not use the proportion module we did?
The proportions.py code
# python_math 1
# proportions
class Prop:
def __init__(self, prop):
'''This is how you put the argument e1 : e2 = m1 : m2
ie: 12 : 3 = 36:9
'''
print(prop)
self.proportion = prop
# replace = with :
prop = prop.replace("=", ":")
# create a list with the numbers, splitting by the ':'
self.prop = prop.split(":")
# converts strings into integers and x to None
for n, x in enumerate(self.prop):
if x.strip() == "x":
self.prop[n] = None
else:
self.prop[n] = int(x)
# memorize in memorable names the extrem and medium terms
e1, m1, m2, e2 = self.prop
self.e1 = e1
self.e2 = e2
self.m1 = m1
self.m2 = m2
self.calculate_x()
def calculate_x(self):
"Call this from the istance to find the incognito"
# Depending on what is None (incognito), it finds it with the other 3
if self.e1 is None:
res = self.m1 * self.m2 / self.e2
elif self.e2 is None:
res = self.m1 * self.m2 / self.e1
elif self.m1 is None:
res = self.e1 * self.e2 / self.m2
elif self.m2 is None:
res = self.e1 * self.e2 / self.m1
print(f"The result of the proportion is {res}\n")
return res
if __name__ == "__main__":
p1 = Prop("12 : 3 = 36 : x")
p2 = Prop("12 : x = 36 : 9")
# percentage proportion
p3 = Prop("100 : 20 = 300 : x")
output
12 : 3 = 36 : x The result of the proportion is 9.0 12 : x = 36 : 9 The result of the proportion is 3.0 100 : 20 = 300 : x The result of the proportion is 60.0
Now let’s see how to make a module for percentage.
The percentage.py code
from proportions import Prop
class Percent(Prop):
def __init__(self, base, percent):
self.base = base
self.percent = percent
prop = f"100 : {percent} = {self.base} : x"
super(Percent, self).__init__(prop)
self.print()
def solve(self):
return self.base * self.percent / 100
def print(self):
print("You find the x this way:")
print(f"x = {self.base} * {self.percent} / 100 = {self.solve()}")
# First the price (for example), then the percent
Percent(3000, 20)
result
100 : 20 = 3000 : x The result of the proportion is 600.0 You find the x this way: x = 3000 * 20 / 100 = 600.0
Video
Github repository
Go here.
Subscribe to the newsletter for updates
Tkinter templatesTwitter: @pythonprogrammi - python_pygame
Claude's Games
1. Memory gameVideos
Speech recognition gamePygame's Platform Game