除了 turtle
模組之外,Python 提供了許多強大且有趣的內建模組和第三方模組,適合各種應用場景。以下是一些你可以學習並使用的 Python 模組:
math
模組import math
print(math.sqrt(16)) # 計算平方根,輸出:4.0
random
模組import random
print(random.randint(1, 10)) # 生成 1 到 10 之間的隨機整數
datetime
模組import datetime
now = datetime.datetime.now()
print(now) # 輸出當前日期和時間
os
模組import os
print(os.getcwd()) # 輸出當前工作目錄
sys
模組import sys
print(sys.argv) # 輸出命令列參數列表
json
模組import json
data = {"name": "Alice", "age": 25}
json_string = json.dumps(data)
print(json_string) # 輸出 JSON 格式字符串
csv
模組import csv
with open('data.csv', mode='r') as file:
csv_reader = csv.reader(file)
for row in csv_reader:
print(row)
collections
模組Counter
、deque
、defaultdict
等。from collections import Counter
data = ["apple", "banana", "apple", "orange"]
counter = Counter(data)
print(counter) # 計算列表中每個元素的出現次數
itertools
模組import itertools
permutations = itertools.permutations([1, 2, 3])
for p in permutations:
print(p)
PIL (Pillow)
模組from PIL import Image
img = Image.open("example.jpg")
img.show() # 打開並顯示圖片
matplotlib
模組import matplotlib.pyplot as plt
plt.plot([1, 2, 3], [4, 5, 6])
plt.show()
requests
模組import requests
response = requests.get("https://jsonplaceholder.typicode.com/posts")
print(response.json())
tkinter
模組import tkinter as tk
window = tk.Tk()
label = tk.Label(window, text="Hello, World!")
label.pack()
window.mainloop()
sqlite3
模組import sqlite3
conn = sqlite3.connect('example.db')
cursor = conn.cursor()
cursor.execute('CREATE TABLE users (id INTEGER, name TEXT)')
conn.commit()
conn.close()
beautifulsoup4
模組requests
一起使用來抓取網頁數據。from bs4 import BeautifulSoup
import requests
response = requests.get('https://example.com')
soup = BeautifulSoup(response.text, 'html.parser')
print(soup.title.text)