Day 114クラスを使った図形面積計算

2026-06-18 JST ・ 難易度: 中級 ・ カテゴリ: 総合演習

Pythonコード

1class Rectangle:2    def __init__(self, width, height):3        self.width = width4        self.height = height5    def area(self):6        return self.width * self.height7 8class Circle:9    def __init__(self, radius):10        self.radius = radius11    def area(self):12        return 3.14 * self.radius ** 213 14while True:15    print("1: \u9577\u65b9\u5f62\u306e\u9762\u4f53\u3092\u8a08\u7b97")16    print("2: \u5713\u306e\u9762\u4f53\u3092\u8a08\u7b97")17    print("3: \u7d42\u4e86")18    choice = input("\u526f\u53f7\u3092\u5165\u529b\u3057\u3066\u304f\u3060\u3057")19    if choice == "1":20        try:21            width = float(input("\u9577\u65b9\u5f62\u306e\u5ea6\u3092\u5165\u529b\u3057\u3066\u304f\u3060\u3057"))22            height = float(input("\u9577\u65b9\u5f62\u306e\u9ad8\u3055\u3092\u5165\u529b\u3057\u3066\u304f\u3060\u3057"))23            rectangle = Rectangle(width, height)24            print(f"\u9577\u65b9\u5f62\u306e\u9762\u4f53\u306f{rectangle.area()}\u3067\u3059")25        except ValueError:26            print("\u6570\u5b57\u3092\u5165\u529b\u3057\u3066\u304f\u3060\u3057")27    elif choice == "2":28        try:29            radius = float(input("\u5713\u306e\u80fd\u5ea6\u3092\u5165\u529b\u3057\u3066\u304f\u3060\u3057"))30            circle = Circle(radius)31            print(f"\u5713\u306e\u9762\u4f53\u306f{circle.area()}\u3067\u3059")32        except ValueError:33            print("\u6570\u5b57\u3092\u5165\u529b\u3057\u3066\u304f\u3060\u3057")34    elif choice == "3":35        break36    else:37        print("\u72b6\u4e0d\u6548\u306a\u526f\u53f7\u3067\u3059")

解説

次に試してみよう