程式碼範例

1
程式碼範例:在程式設計的學習旅程中,程式碼範例 是最直接、最有效的教學媒介。它們如同廚房裡的食譜,不僅展示最終成果,更一步步分解複雜問題的解決過程。程式碼範例跨越語言與領域,從簡單的Hello World到企業級架構實作,都是開發者快速上手、理解最佳實踐的捷徑。優質範例不僅教語法,更傳遞工程思維、設計哲學與除錯技巧,是每個程式設計師的成長加速器。

程式碼範例

程式碼範例:從入門到實戰的程式設計教科書

在程式設計的學習旅程中,程式碼範例 是最直接、最有效的教學媒介。它們如同廚房裡的食譜,不僅展示最終成果,更一步步分解複雜問題的解決過程。程式碼範例跨越語言與領域,從簡單的Hello World到企業級架構實作,都是開發者快速上手、理解最佳實踐的捷徑。優質範例不僅教語法,更傳遞工程思維、設計哲學與除錯技巧,是每個程式設計師的成長加速器。

程式碼範例是開源文化的精髓,GitHub上億萬行示範代碼免費共享,讓全球開發者站在巨人的肩膀上創新。理解如何閱讀、修改、重用範例,就是掌握程式設計的真正秘訣。

 


一、程式碼範例的分類體系:不同學習階段的最佳教材

入門範例:建立信心基礎

Hello World(各語言對比)

# Python - 最簡潔
print("Hello, World!")
 

// JavaScript - 瀏覽器控制台
console.log("Hello, World!");
 

// Java - 完整結構
public class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello, World!");
    }
}
 

計算器範例

def calculator():
    while True:
        try:
            num1 = float(input("第一個數字:"))
            op = input("運算子 (+-*/): ")
            num2 = float(input("第二個數字:"))
            
            if op == '+': result = num1 + num2
            elif op == '-': result = num1 - num2
            elif op == '*': result = num1 * num2
            elif op == '/':
                if num2 == 0: raise ValueError("除數不能為零")
                result = num1 / num2
            else: print("無效運算子")
                continue
                
            print(f"結果:{result}")
            if input("繼續?(y/n): ").lower() != 'y': break
        except ValueError as e:
            print(f"錯誤:{e}")

calculator()

 

中階範例:資料結構與演算法

二分搜尋法

def binary_search(arr, target):
    """
    在已排序陣列中二分搜尋目標值
    時間複雜度:O(log n)
    """
    left, right = 0, len(arr) - 1
    
    while left <= right:
        mid = (left + right) // 2
        
        if arr[mid] == target:
            return mid  # 找到目標索引
        elif arr[mid] < target:
            left = mid + 1  # 搜尋右半區
        else:
            right = mid - 1  # 搜尋左半區
    
    return -1  # 未找到

# 使用範例
numbers = [1, 3, 5, 7, 9, 11, 13, 15]
print(binary_search(numbers, 7))  # 輸出:3
 

二、前端開發實戰範例:網頁互動的核心

響應式導航選單

<!DOCTYPE html>
<html>
<head>
    <style>
        .nav { display: flex; }
        .hamburger { display: none; }
        @media (max-width: 768px) {
            .nav { display: none; }
            .nav.active { display: flex; flex-direction: column; }
            .hamburger { display: block; }
        }
    </style>
</head>
<body>
    <nav class="nav" id="nav">
        <a href="/">首頁</a>
        <a href="/about">關於</a>
        <a href="/services">服務</a>
        <a href="/contact">聯絡</a>
    </nav>
    <button class="hamburger" onclick="toggleNav()">☰</button>

    <script>
        function toggleNav() {
            const nav = document.getElementById('nav');
            nav.classList.toggle('active');
        }
    </script>
</body>
</html>

 

即時搜尋過濾

// 搜尋過濾器(用於產品清單、文章列表)
function setupSearchFilter() {
    const searchInput = document.getElementById('search');
    const items = document.querySelectorAll('.item');
    
    searchInput.addEventListener('input', (e) => {
        const query = e.target.value.toLowerCase();
        
        items.forEach(item => {
            const text = item.textContent.toLowerCase();
            item.style.display = text.includes(query) ? 'block' : 'none';
        });
    });
}
 

三、後端API開發範例:RESTful服務實作

Express.js完整CRUD API

const express = require('express');
const app = express();
app.use(express.json());

// 模擬資料庫
let users = [
    { id: 1, name: 'Alice', email: '[email protected]' },
    { id: 2, name: 'Bob', email: '[email protected]' }
];

// GET /users - 取得所有使用者
app.get('/users', (req, res) => {
    res.json(users);
});

// GET /users/:id - 單一使用者
app.get('/users/:id', (req, res) => {
    const user = users.find(u => u.id === parseInt(req.params.id));
    if (!user) return res.status(404).json({ error: 'User not found' });
    res.json(user);
});

// POST /users - 新增使用者
app.post('/users', (req, res) => {
    const { name, email } = req.body;
    if (!name || !email) {
        return res.status(400).json({ error: 'Name and email required' });
    }
    
    const newUser = {
        id: users.length + 1,
        name,
        email
    };
    users.push(newUser);
    res.status(201).json(newUser);
});

// PUT /users/:id - 更新使用者
app.put('/users/:id', (req, res) => {
    const id = parseInt(req.params.id);
    const userIndex = users.findIndex(u => u.id === id);
    
    if (userIndex === -1) {
        return res.status(404).json({ error: 'User not found' });
    }
    
    users[userIndex] = { ...users[userIndex], ...req.body };
    res.json(users[userIndex]);
});

// DELETE /users/:id
app.delete('/users/:id', (req, res) => {
    const id = parseInt(req.params.id);
    const userIndex = users.findIndex(u => u.id === id);
    
    if (userIndex === -1) {
        return res.status(404).json({ error: 'User not found' });
    }
    
    users.splice(userIndex, 1);
    res.status(204).send();
});

app.listen(3000, () => {
    console.log('Server running on port 3000');
});
 

四、資料處理與分析範例:Python資料科學經典

CSV資料讀取與分析

import pandas as pd
import matplotlib.pyplot as plt

# 讀取銷售資料
df = pd.read_csv('sales.csv')

# 資料清理
df['date'] = pd.to_datetime(df['date'])
df = df.dropna(subset=['sales_amount'])

# 按月聚合
monthly_sales = df.groupby(df['date'].dt.to_period('M'))['sales_amount'].sum()

# 繪製趨勢圖
monthly_sales.plot(kind='line', title='每月銷售趨勢')
plt.ylabel('銷售金額')
plt.show()

# Top 5產品
top_products = df.groupby('product')['sales_amount'].sum().nlargest(5)
print("Top 5產品: ", top_products)
 

資料庫連線與查詢

import sqlite3
from contextlib import contextmanager

@contextmanager
def get_db_connection():
    conn = sqlite3.connect('store.db')
    try:
        yield conn
    finally:
        conn.close()

def get_top_sellers(limit=10):
    with get_db_connection() as conn:
        query = """
        SELECT p.name, SUM(oi.quantity * oi.unit_price) as total_sales
        FROM products p
        JOIN order_items oi ON p.id = oi.product_id
        GROUP BY p.id, p.name
        ORDER BY total_sales DESC
        LIMIT ?
        """
        return pd.read_sql_query(query, conn, params=(limit,))
 

五、演算法經典範例:面試必備解題模板

反轉鏈結串列

class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next

def reverseList(head):
    """
    反轉單向鏈結串列 O(n)時間 O(1)空間
    """
    prev = None
    current = head
    
    while current:
        next_temp = current.next      # 暫存下一個節點
        current.next = prev           # 反轉指針
        prev = current                # 前進
        current = next_temp           # 前進
        
    return prev  # 新頭節點

# 使用範例
# 1 -> 2 -> 3 -> None 變成 3 -> 2 -> 1 -> None
 

LRU快取實作

class LRUCache:
    def __init__(self, capacity):
        self.capacity = capacity
        self.cache = {}
        self.order = []
    
    def get(self, key):
        if key not in self.cache:
            return -1
        
        # 移到最近使用
        self.order.remove(key)
        self.order.append(key)
        return self.cache[key]
    
    def put(self, key, value):
        if key in self.cache:
            self.order.remove(key)
        elif len(self.cache) >= self.capacity:
            # 移除最久未使用
            lru_key = self.order.pop(0)
            del self.cache[lru_key]
        
        self.cache[key] = value
        self.order.append(key)
 

六、安全與最佳實踐範例:生產環境標準

安全的表單處理

// Express + 驗證 + 消毒 + CSRF防護
app.post('/register', [
    // 驗證
    body('email').isEmail().normalizeEmail(),
    body('password').isLength({ min: 8 }),
    // CSRF檢查
], (req, res) => {
    // 消毒
    const { email, password } = req.body;
    
    // 雜湊密碼
    const hashedPassword = bcrypt.hashSync(password, 12);
    
    // 參數化查詢
    db.query(
        'INSERT INTO users (email, password_hash) VALUES (?, ?)',
        [email, hashedPassword],
        (err) => {
            if (err) return res.status(500).json({ error: '註冊失敗' });
            res.status(201).json({ message: '註冊成功' });
        }
    );
});
 

七、結語:程式碼範例,程式設計的活教材

程式碼範例是程式設計的活化石,每行代碼背後都凝結實戰經驗與工程智慧。從簡單的計算器到複雜的微服務架構,每個範例都是問題解決的藍圖。

優秀開發者不是記住所有語法,而是學會閱讀範例、理解模式、靈活修改。開源世界億萬行範例代碼,等著你fork、修改、貢獻。當你從複製範例到創造自己的解決方案,那一刻,你已成為真正的程式設計師。程式碼範例,不只是學習工具,更是創新的起點。