| 28 | |
| 29 | |
| 30 | class Square: |
| 31 | def __init__(self, side=None): |
| 32 | if side is None: |
| 33 | self.ask_side() |
| 34 | # else: |
| 35 | # self.side = float(side) |
| 36 | else: |
| 37 | if not isinstance(side, (int, float)): |
| 38 | try: |
| 39 | side = float(side) |
| 40 | except ValueError: |
| 41 | # return "Invalid input for side." |
| 42 | raise ValueError("Invalid input for side.") |
| 43 | else: |
| 44 | self.side = float(side) |
| 45 | # Check if the result is a float and remove unnecessary zeros |
| 46 | |
| 47 | self.calculate_square() |
| 48 | self.truncate_decimals() |
| 49 | |
| 50 | # If ask side or input directly into the square. |
| 51 | # That can be done? |
| 52 | def calculate_square(self): |
| 53 | self.area = self.side * self.side |
| 54 | return self.area |
| 55 | |
| 56 | # Want to add a while loop asking for the input. |
| 57 | # Also have an option to ask the user in true mode or in repeat mode. |
| 58 | def ask_side(self): |
| 59 | # if true bool then while if int or float then for loop. |
| 60 | # I will have to learn inheritance and polymorphism. |
| 61 | condition = 3 |
| 62 | # condition = True |
| 63 | if condition == True and isinstance(condition, bool): |
| 64 | while condition: |
| 65 | n = input("Enter the side of the square: ") |
| 66 | self.side = float(n) |
| 67 | elif isinstance(condition, (int, float)): |
| 68 | for i in range(_=condition): |
| 69 | n = input("Enter the side of the square: ") |
| 70 | self.side = float(n) |
| 71 | # n = input("Enter the side of the square: ") |
| 72 | # self.side = float(n) |
| 73 | # return |
| 74 | |
| 75 | def truncate_decimals(self): |
| 76 | return ( |
| 77 | f"{self.area:.10f}".rstrip("0").rstrip(".") |
| 78 | if "." in str(self.area) |
| 79 | else self.area |
| 80 | ) |
| 81 | |
| 82 | # Prettifying the output. |
| 83 | |
| 84 | def calculate_perimeter(self): |
| 85 | return 4 * self.side |
| 86 | |
| 87 | def calculate_perimeter_prettify(self): |