將此提示複製到我們的開發者 Console 來親自試試看!

內容
System你的任務是分析提供的 Python 程式碼片段,識別其中存在的任何錯誤或問題,並提供一個已修正的程式碼版本來解決這些問題。解釋你在原始程式碼中發現的問題,以及你的修正如何解決這些問題。修正後的程式碼應該是可運作的、高效的,並且遵循 Python 程式設計的最佳實踐。
Userdef calculate_average(nums):
sum = 0
for num in nums:
sum += num
average = sum / len(nums)
return average

numbers = [10, 20, 30, 40, 50]
result = calculate_average(numbers)
print(“The average is:”, results)

範例輸出

修正後的 Python 程式碼:

Python
def calculate_average(nums):
    total = 0
    for num in nums:
        total += num
    average = total / len(nums)
    return average

numbers = [10, 20, 30, 40, 50]
result = calculate_average(numbers)
print("The average is:", result)

說明:

  1. 將變數名稱 “sum” 改為 “total”,以避免使用 Python 內建函數 “sum()”。
  2. 修正 print 語句中的拼寫錯誤,將 “results” 改為 “result” 以正確引用變數。

API 請求

import anthropic

client = anthropic.Anthropic(
  # 預設使用 os.environ.get("ANTHROPIC_API_KEY")
  api_key="my_api_key",
)
message = client.messages.create(
  model="claude-3-7-sonnet-20250219",
  max_tokens=1000,
  temperature=0,
  system="Your task is to analyze the provided Python code snippet, identify any bugs or errors present, and provide a corrected version of the code that resolves these issues. Explain the problems you found in the original code and how your fixes address them. The corrected code should be functional, efficient, and adhere to best practices in Python programming.",
  messages=[
    {
    "role": "user",
    "content": [
        {
          "type": "text",
          "text": "def calculate_average(nums):\n sum = 0\n for num in nums:\n sum += num\n average = sum / len(nums)\n return average\n\nnumbers = [10, 20, 30, 40, 50]\nresult = calculate_average(numbers)\nprint(\"The average is:\", results)"
        }
      ]
    }
  ]
)
print(message.content)