Read the question, write Python on the right, then Run or Check.
QuestionHint and solution stay closed until you open them
Read a width and a height (one per line). Build a Rectangle class with area() and perimeter() methods and print both.
Print two lines exactly: "Area: X" then "Perimeter: Y". This is your first taste of bundling data and behaviour into one object.
Input. Two lines: width, then height (integers).
Output. Line 1: Area: <area>. Line 2: Perimeter: <perimeter>.
Constraints
- 1 ≤ width, height ≤ 10000
Examples
Input
4 3
Output
Area: 12 Perimeter: 14
Hint
- Store width and height in __init__ as self.w and self.h.
- area() returns self.w * self.h; perimeter() returns 2 * (self.w + self.h).
Show correct code
Peek only after you have tried. You can still Check your own version.
class Rectangle:
def __init__(self, w, h):
self.w = w
self.h = h
def area(self):
return self.w * self.h
def perimeter(self):
return 2 * (self.w + self.h)
w = int(input())
h = int(input())
r = Rectangle(w, h)
print(f"Area: {r.area()}")
print(f"Perimeter: {r.perimeter()}")
main.pyPython · Ctrl + Enter runs
ResultIdle
Run to see output. Check grades the tests.