Start free

Advanced · Classes · 195 of 264

Shapes

Write a base class Shape with an area() method and subclasses Circle, Rectangle and Square. Read shapes and print their areas from the largest to the smallest, with two decimals.

Input: n, then lines like circle 2, rectangle 3 4, square 5. Output: lines like square 25.00

Examples

Input
3
circle 2
rectangle 3 4
square 5
Output
square 25.00
circle 12.57
rectangle 12.00
Input
1
square 1
Output
square 1.00

One more test checks other inputs when you press Check.

Stuck? The idea behind classes

A class describes a kind of object: its data (attributes, set in __init__) and what it can do (methods). Each object made from it has its own data.

self is the object a method is called on; __str__ says how the object prints.

class Account:
    def __init__(self, owner):
        self.owner = owner
        self.balance = 0

    def pay_in(self, amount):
        self.balance += amount

acc = Account("Ann")
acc.pay_in(5)
print(acc.balance)

Watch for: Every method's first parameter is self, and attributes are reached through it: self.balance, not balance.

All the classes exercises
Your code
Opening the code editor…
Python 3.14 in your browser
Output
Run shows what your program prints. Check tests it on every example and the hidden tests.

More classes exercises