如何用PYTHON計算出矩形的面積
如何用PYTHON計算出矩形的面積
操作方法
(01)開啟JUPTER NOTEBOOK,新建一個PY文件。
(02)width = 5length = 6size = width * lengthprint(size)定義三個變數,然後直接列印最後一個變數,這是一種方法。
(03)width = input("Please input the width: ")length = input("Please input the width: ")size = width * lengthprint(size)也可以用INPUT,但是要注意這樣會出現問題的。
(04)width = int(input("Please input the width: "))length = int(input("Please input the width: "))size = width * lengthprint(size)字元串是不能做運算的,但是整型是可以的。
(05)width = float(input("Please input the width: "))length = float(input("Please input the width: "))size = width * lengthprint(size)如果有小數點的話那麼就要用浮點型了。
(06)class Retangle():def __init__(self, width, length):h = th = length我們定義一下新的類。
(07)def size(self):return h * thshape = Retangle(5, 6)print(shape)可以看到這樣得不到我們要的結果。
(08)原因就是我們後面定義的size不能再後面定義,要在定義類的時候一起定義。
(09)只要分開都會出現問題。
(10)class Retangle():def __init__(self, width, length):h = th = lengthdef size(self):return h * th在同一個方格製作就可以得到結果了。
特別提示
注意class的運用