WeHelp
學習各式各樣的內建函式、類別、物件、模組等等工具,完成各種 Python 基礎應用。
  1. 字串的操作
  2. 列表的操作
  3. 字典的操作
  4. 數學、統計模組
  5. 文字檔案讀取、寫入
  6. CSV 檔案讀取、寫入
  7. JSON 檔案讀取、寫入
  8. ZIP 壓縮檔案和解壓縮
  9. HTTP 網路連線請求
  10. 網頁爬蟲程式
  11. 日期與時間
  12. 正規表達式
數學、統計模組
Python 提供兩個常用的標準函式庫模組:`math` 與 `statistics`。使用前需先匯入模組。 ## 1. `math` 數學模組 `math` 提供常見的數學常數與函式,例如平方根、次方、對數、三角函數、無條件進位等。 ### 常用功能 ```python import math math.pi # 圓周率 math.sqrt(25) # 平方根:5.0 math.pow(2, 3) # 次方:8.0 math.ceil(3.2) # 無條件進位:4 math.floor(3.8) # 無條件捨去:3 math.sin(math.pi / 2) # sin(90°):1.0 ``` ### 實務範例:計算圓形地板所需的磁磚數 假設要鋪設半徑為 3 公尺的圓形地板,每片磁磚可鋪設 `0.5` 平方公尺,計算至少需要幾片磁磚。 ```python import math radius = 3 tile_area = 0.5 floor_area = math.pi * math.pow(radius, 2) tile_count = math.ceil(floor_area / tile_area) print(f"地板面積:約 {floor_area:.2f} 平方公尺") print(f"至少需要 {tile_count} 片磁磚") ``` 輸出: ```text 地板面積:約 28.27 平方公尺 至少需要 57 片磁磚 ``` 使用 `math.ceil()` 是因為磁磚數量不能出現小數,且必須向上取整數。 --- ## 2. `statistics` 統計模組 `statistics` 提供基本統計計算功能,適合處理數值資料,例如平均數、中位數、眾數與標準差。 ### 常用功能 ```python import statistics data = [10, 20, 20, 30, 40] statistics.mean(data) # 平均數 statistics.median(data) # 中位數 statistics.mode(data) # 眾數 statistics.stdev(data) # 樣本標準差 statistics.pstdev(data) # 母體標準差 ``` ### 實務範例:分析學生考試成績 ```python import statistics scores = [78, 85, 92, 85, 60, 73, 88] average = statistics.mean(scores) median = statistics.median(scores) most_common = statistics.mode(scores) standard_deviation = statistics.stdev(scores) print(f"平均分數:{average:.2f}") print(f"中位數:{median}") print(f"最常出現的分數:{most_common}") print(f"樣本標準差:{standard_deviation:.2f}") ``` 可能輸出: ```text 平均分數:80.14 中位數:85 最常出現的分數:85 樣本標準差:10.42 ``` 透過這些統計量,可以了解整體平均表現、典型成績,以及成績分散程度。 ## 總結 | 模組 | 主要用途 | 常用函式 | |---|---|---| | `math` | 數學運算 | `sqrt()`、`pow()`、`ceil()`、`floor()`、`sin()` | | `statistics` | 基本統計分析 | `mean()`、`median()`、`mode()`、`stdev()` | 兩者都屬於 Python 標準函式庫,不需要另外安裝,直接使用 `import` 即可。
相關學習地圖、教學課程
Python 資料工程
從 0 開始,成為資料工程師的學習路徑。
Python 後端工程、資料庫
從 0 開始,成為後端工程師的學習路徑。