開始使用免費開始

使用 Claude Code 來除錯 Python 程式碼

你的同事回報一個奇怪的錯誤:analytics.py 裡的 calculate_average_tracks() 函式回傳了不正確的數值。當用 3 張專輯測試,曲目數分別為 10、12、8 時,這個函式回傳了 30,而不是預期的平均值 10。

以下是 analytics.py 中的函式:

def calculate_average_tracks(albums):
    """Calculate average number of tracks per album.

    Returns the average track count across all albums.
    """
    total = sum(album.get('track_count', 0) for album in albums)
    return total  # Bug: should return total / len(albums)

    # Bug reproduction:
    # albums = [{'track_count': 10}, {'track_count': 12}, {'track_count': 8}]
    # print(calculate_average_tracks(albums))  # Returns 30, should return 10

本練習屬於課程

使用 Claude Code 進行軟體開發

檢視課程

練習說明

  • 使用 claude 啟動 Claude Code。
  • 請 Claude 分析 analytics.py 並找出 calculate_average_tracks() 的錯誤。
  • 請 Claude 修正這個錯誤。
  • 完成後,輸入 /exit 以離開 Claude Code。

動手互動練習

將理論付諸實踐,立即體驗我們的互動練習

開始練習