1
\$\begingroup\$

My program looks for the area of ​​the figures, depending on the value of the variable а.

  1. area -> triangle

  2. area -> triangle2

  3. area -> square

  4. area -> rhombus

    I want to get constructive criticism about the structure of the code and what can be redone. The program is written in the Python programming language.

while True:
    class S():
        print("Для выхода нажмите Enter")
        a = int(input("1. Площадь прямоугольного тр. \n2. Площадь равнобедренного тр. \n3. Площадь квадрата \n4. Площадь ромба  "))
        if a == 1:
            print("Это нахождение площади прямоугольного треугольника")
            a1 = float(input("Введите первый катет  "))
            b1 = float(input("Введите второй катет  "))
            class Triangle1():
                    def  __init__(self, a1, b1):
                        self.a = a1
                        self.b = b1
                    def area(self):
                        return (self.a * self.b) / 2
            Striangle1 = Triangle1(a1,b1)        
            print("Площадь равна = ",Striangle1.area())
        elif a == 2:
            print("Это нахождение площади равнобедренного треугольника")
            a2 = float(input("Введите основание  "))
            b2 = float(input("Введите высоту  "))
            class Triangle2():
                    def  __init__(self, a2, b2):
                        self.a2 = a2
                        self.b2 = b2
                    def area(self):
                        return (self.a2/2)*self.b2
            Striangle2 = Triangle2(a2,b2)        
            print("Площадь равна = ",Striangle2.area())
        if a == 3:
            print("Это нахождение площади квадрата  ")
            a3 = float(input("Введите сторону  "))
            class Hexagon():
                def __init__(self, a3):    
                    self.a3 = a3
                def area(self):
                    return self.a3**2
            Shexagon = Hexagon(a3)
            print("Площадь равна = ",Shexagon.area())            
        elif a == 4:
            print("Это нахождение площади ромба")
            a4 = float(input("Введите 1 диагональ  "))
            b4 = float(input("Введите 2 диагональ  "))
            class Romb():
                def  __init__(self, a4, b4):
                    self.a4 = a4
                    self.b4 = b4
                def area(self):
                    return (self.a4*self.b4)/2
            Sromb = Romb(a4,b4)        
            print("Площадь равна = ",Sromb.area())        

Drive link to the code

\$\endgroup\$
1
  • 2
    \$\begingroup\$ Hi @feraun! Could you please convert those input prompts to English? Thanks! \$\endgroup\$
    – aki
    Feb 1, 2020 at 18:41

2 Answers 2

3
\$\begingroup\$

First, note that finding the area of an isosceles triangle is the same formula as finding the area of right triangle. Both are 1/2 * base * height.

You are mixing object oriented classes and imperative programming. This usually happens as you are first learning about classes. Here is are two alternate structures to your code:

First option, you can ignore classes. The only commonality between a triangle and an octagon is that both have an area() method. There is no common data: a triangle has no radius and an octagon has nothing but a radius. You can make functions like triangle_area(base, height), octagon_radius(radius). Both return areas. Just doing this would simplify your code.

Second option, you use classes anyway. You might do this if you expect more commonality in the near future. For example, if this is becoming a drawing program then a Figure might be a class that "has a x,y center, current color, a move command, a draw command and an area function." This code would have code common to all figures in class Figure and would have empty (or virtual) routines that are 'parts any subclass needs to implement to considered a Figure'.

Here is some a code outline to ponder:

 class Figure:
     def area(self):  # return the area of this figure
         raise NotImplementedExeception('subclass must have an area() function')

 class Triangle(Figure):   # inheritence is the promise to follow the superclass API
     def __init__(self, base, height):
         super().__init__()   # this is boilerplate
         self.base, self.height = base, height

     def area(self):
         return self.base * self.height / 2

     @classmethod  # used for custom constructors
     def ask_right(cls):
        print("Это нахождение площади прямоугольного треугольника")
        a1 = float(input("Введите первый катет  "))
        b1 = float(input("Введите второй катет  "))
        return cls(a1, a2)   # return a new triangle

     @classmethod
     def ask_isosceles():
        ...

def main():
        print("Для выхода нажмите Enter")
        a = int(input("1. Площадь прямоугольного тр. \n2. Площадь равнобедренного тр. \n3. Площадь квадрата \n4. Площадь ромба  "))
        if a == 1:
            fig = Triangle.ask_right()
        elif a == 2:
            fig = Triangle.ask_isosceles()
        elif a == 3:
            fig = Octagon.ask()

        print f"Area is {fig.area()}")

In summary, using classes to organize your code makes more sense if you are doing more than just one item. The real power comes from being able to write functions like:

def redraw(list_of_figures):
    clear_screen()
    for fig in list_of_figures:
        fig.draw()   # which might be Circle.draw(), Triangle.draw() or another subclass

and adding a new subclass, say Pentagon(Figure), without having to change the redraw() function.

Classes can be hard to get your head around; that is normal.

Keep hacking! Keep notes.

\$\endgroup\$
2
\$\begingroup\$

There are several ways to improve this code:

  1. Commenting. Please add some comments to your code so other people can understand it easily. It might not be a "coding" suggestion but it is as important as writing a good code.
  2. Classes declaration location. It is not usual to declare the classes inside the main loop area. You can declare them outside, maybe even in another file.
  3. Use meaningful variables names.
  4. Use type annotations. To make the code faster and more readable.
  5. Remove redundant class. Class S is redundant and should probably be removed since it has no real functionality.
  6. Create a general class. All of your classes can inherit from a general shape class and override the area method.
  7. Remove redundant parentheses. Remove redundant parentheses in the classes declarations.
  8. Use fstring while printing.
  9. Do not write code in main. Create a function that __main__ will call so none of your variables will be global.

As said there are several ways to improve this code. All of them are suggestion and you do not have to implement any of them. This is a functioning and understandable code as is.

I know you asked us to rate your code, but I will not :)
Keep programing!

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.