Python 的內建函式(Built-in Functions)與標準庫(Standard Library),能讓我們寫程式時事半功倍。
(1) len()
取得長度:
print(len("hello")) # 5
print(len([1, 2, 3])) # 3
(2) type()
檢查資料型態:
print(type(123)) # <class 'int'>
print(type([1,2])) # <class 'list'>
(3) range()
產生數字序列(常用於迴圈):
for i in range(1, 6):
print(i)
(4) sum()
快速加總:
nums = [1, 2, 3, 4]
print(sum(nums)) # 10
(5) max() / min()
找最大或最小值:
print(max([3, 9, 5])) # 9
print(min([3, 9, 5])) # 3
(6) sorted()
排序:
nums = [4, 1, 7, 3]
print(sorted(nums)) # [1, 3, 4, 7]
print(sorted(nums, reverse=True)) # [7, 4, 3, 1]
(7) map() / filter()
函式式處理資料:
nums = [1, 2, 3, 4, 5]
squares = list(map(lambda x: x**2, nums)) # map:平方
evens = list(filter(lambda x: x % 2 == 0, nums)) # filter:篩選偶數
print(squares) # [1, 4, 9, 16, 25]
print(evens) # [2, 4]
(1) datetime:處理日期與時間
import datetime
now = datetime.datetime.now()
print("現在時間:", now)
next_week = now + datetime.timedelta(days=7)
print("一週後:", next_week)
(2) math:數學計算
import math
print(math.sqrt(16)) # 4.0
print(math.pow(2, 3)) # 8.0
print(math.pi) # 3.141592653589793
(3) random:隨機數
import random
print(random.randint(1, 10)) # 隨機整數
print(random.choice(["🍎", "🍌", "🍇"])) # 隨機選一個水果
(4) os:系統操作
import os
print(os.getcwd()) # 目前路徑
print(os.listdir(".")) # 列出目錄檔案
(5) sys:Python 系統資訊
import sys
print(sys.version) # Python 版本
print(sys.platform) # 系統平台
(6) json:處理 JSON 格式(常用於 API 資料交換)
import json
person = {"name": "Allen", "age": 25}
json_str = json.dumps(person) # 轉換為 JSON 字串
print(json_str)
data = json.loads(json_str) # 轉回 Python dict
print(data["name"])
def generate_password(length=8):
chars = string.ascii_letters + string.digits + string.punctuation
return "".join(random.choice(chars) for _ in range(length))
print("隨機密碼:", generate_password(12))
使用 random + string,幾行程式就能完成。
學會了Python的內建函式與標準庫,了解如何善用這些隱藏武器。
明天,將進入檔案操作(File Handling),學習如何讀寫檔案,讓程式能真正和外部世界互動。