Complete Square and Circle so that both work through the same area() method. Print each area with two decimal places.
What to build
Two shapes that share one interface.
Requirements
- Complete
SquareandCircleso that each has its ownarea(). - Print each area with two decimal places.
Input
The first line has n (1 to 50). Each of the next n lines is square SIDE or circle RADIUS, with a whole number from 1 to 1000.
Output
One area per line, with two decimal places.
Constraints
n is from 1 to 50, and sizes are from 1 to 1000.
Example
Input:
2
square 4
circle 1
Output:
16.00
3.14
Why it works
The caller only needs to know that every shape has area(), so a new shape needs no change to the loop.
Examples
Example 1 · Input
2 square 4 circle 1
Expected output
16.00 3.14
Example 2 · Input
1 square 1
Expected output
1.00
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
Give each child class its own area method.
Hint 2
A circle's area is math.pi * r * r.
Solution
Show one correct solution (try it yourself first)
import math
class Shape:
def area(self):
return 0
class Square(Shape):
def __init__(self, side):
self.side = side
def area(self):
return self.side * self.side
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
return math.pi * self.radius * self.radius
n = int(input())
for _ in range(n):
kind, size = input().split()
shape = Square(int(size)) if kind == "square" else Circle(int(size))
print(f"{shape.area():.2f}")