Python 模組:標準模組、自定義模組與模組管理
模組是 Python 中用於組織程式碼的方式,一個模組通常是包含一組函數、類別或變數的 Python 文件(.py)。模組的作用是重用代碼、提高可讀性並便於維護。Python 提供了大量內建模組(標準模組庫),同時允許開發者創建自己的模組。
標準模組庫(Standard Library)
Python 提供豐富的標準模組庫,例如 math、os、random 等,可以直接導入使用,無需安裝。
第三方模組(Third-Party Modules)
由社群或公司開發的模組,需要使用 pip 進行安裝,例如 numpy、pandas。
自定義模組(Custom Modules)
開發者自己創建的模組,通常用於專案內部的功能封裝。
首先使用math模組,計算圓面積 π * r^2
import math |
接著定義calculate_circle_area
def calculate_circle_area(radius): area = math.pi * radius**2 # ** means square return area |
讓使用者輸入半徑,即可得出圓面積 π * r^2
radius = float(input("Enter the radius of the circle you want calculate: "))area = calculate_circle_area(radius)print(f"radius:{radius} area:{area} pi:{math.pi}") |
- 使用 random 模組隨機生成一個 1 到 10 的數字,並讓使用者猜測
使用random模組,先隨機產生1~10其中一個數字,然後while True,直到使用者猜中數字。
import random |
def guess_number():number_to_guess = random.randint(1, 10)while True: guess = int(input("Guess a number between 1 and 10: ")) if guess == number_to_guess: print("Right") break elif guess > number_to_guess: print("Guess too high, try again") else: print("Guess too low, try again") |
- 創建一個名為 my_utils.py 的模組,包含一個簡單的 greet() 函數,並在主程式中導入並使用這個模組。
先創好一個my_utils.py的檔案,內容如下
def greet(name): return f"Hello, {name} Welcome!" |
在回到原本的.py檔案,import my_utils,即可使用my_utils.py裡所定義的functions
import my_utils name = input("Enter your name: ")greeting_messge = my_utils.greet(name)print(greeting_messge) |
文章標籤
全站熱搜

美國魔根 https://www.tw9g.com/goods/pro226.html