Библиотека промптов
Отладчик Python
Ресурсы
- Overview
- Быстрый старт
- Карточка модели Claude 3
- Системная карта Claude 3.7
- Статус системы
- Курсы Anthropic
- Библиотека промптов
- Библиотека промптов
- Космические клавиши
- Корпоративный ясновидящий
- Мастер создания веб-сайтов
- Эксперт по формулам Excel
- Разработчик скриптов Google Apps
- Отладчик Python
- Консультант по путешествиям во времени
- Помощник по сторителлингу
- Цитируйте свои источники
- SQL-волшебник
- Толкователь снов
- Каламбурщик
- Кулинарный создатель
- Поэт портманто
- Хэл - юмористический помощник
- LaTeX справочник
- Цветовой определитель настроения
- Git gud
- Мастер сравнений
- Навигатор по этическим дилеммам
- Протоколист совещаний
- Толкователь идиом
- Консультант по коду
- Создатель функций
- Создатель неологизмов
- Конвертер CSV
- Эмодзи-кодировщик
- Шлифовщик прозы
- Анализатор перспектив
- Генератор викторин
- Наставник по осознанности
- Упроститель для второклассников
- Инноватор фитнеса в VR
- Очиститель PII
- Мастер служебных записок
- Карьерный коуч
- Эксперт по оценке
- Скороговорки
- Составитель вопросов для собеседования
- Гений грамматики
- Загадай-ка мне загадку
- Пояснитель кода
- Инопланетный антрополог
- Организатор данных
- Создатель бренда
- Оценщик эффективности
- Классификатор отзывов
- Преобразователь указаний
- Мотивационная муза
- Извлечение email-адресов
- Мастер-модератор
- Планировщик уроков
- Сократический мудрец
- Алхимик аллитераций
- Футуристический консультант по моде
- Полиглот-суперсилы
- Профессионал по названиям продуктов
- Философские размышления
- Волшебник электронных таблиц
- Симулятор научно-фантастических сценариев
- Адаптивный редактор
- Вещание Вавилона
- Определитель тона твитов
- Анализатор кодов аэропортов
Библиотека промптов
Отладчик Python
Обнаружение и исправление ошибок в коде Python.
Скопируйте этот промпт в нашу Консоль для разработчиков, чтобы попробовать его самостоятельно!
Content | |
---|---|
System | Ваша задача — проанализировать предоставленный фрагмент кода Python, выявить любые ошибки или баги, и предоставить исправленную версию кода, которая решает эти проблемы. Объясните проблемы, которые вы нашли в исходном коде, и как ваши исправления их устраняют. Исправленный код должен быть функциональным, эффективным и соответствовать лучшим практикам программирования на Python. |
User | def 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)
Объяснение:
- Изменено имя переменной “sum” на “total”, чтобы избежать использования встроенной функции Python “sum()”.
- Исправлена опечатка в операторе print, заменив “results” на “result” для правильной ссылки на переменную.
API-запрос
import anthropic
client = anthropic.Anthropic(
# defaults to 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)
import anthropic
client = anthropic.Anthropic(
# defaults to 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)
import Anthropic from "@anthropic-ai/sdk";
const anthropic = new Anthropic({
apiKey: "my_api_key", // defaults to process.env["ANTHROPIC_API_KEY"]
});
const msg = await anthropic.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)"
}
]
}
]
});
console.log(msg);
from anthropic import AnthropicBedrock
# See https://docs.anthropic.com/claude/reference/claude-on-amazon-bedrock
# for authentication options
client = AnthropicBedrock()
message = client.messages.create(
model="anthropic.claude-opus-4-20250514-v1:0",
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)
import AnthropicBedrock from "@anthropic-ai/bedrock-sdk";
// See https://docs.anthropic.com/claude/reference/claude-on-amazon-bedrock
// for authentication options
const client = new AnthropicBedrock();
const msg = await client.messages.create({
model: "anthropic.claude-opus-4-20250514-v1:0",
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)"
}
]
}
]
});
console.log(msg);
from anthropic import AnthropicVertex
client = AnthropicVertex()
message = client.messages.create(
model="claude-3-7-sonnet-v1@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)
import { AnthropicVertex } from '@anthropic-ai/vertex-sdk';
// Reads from the `CLOUD_ML_REGION` & `ANTHROPIC_VERTEX_PROJECT_ID` environment variables.
// Additionally goes through the standard `google-auth-library` flow.
const client = new AnthropicVertex();
const msg = await client.messages.create({
model: "claude-3-7-sonnet-v1@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)"
}
]
}
]
});
console.log(msg);
Was this page helpful?
On this page