將此提示複製到我們的開發者控制台中,親自嘗試!

內容
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. 修復了打印語句中的拼寫錯誤,將 “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-opus-4-20250514",
  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)