Getting Started with Python Using Claude Code
Claude Code is a terminal-based AI assistant that reads your files, runs commands, edits code, and iterates on errors. You type what you want in plain English. Claude Code figures out which files to read, which commands to run, and what code to write. When something breaks, it reads the error, adjusts, and tries again.
This guide covers how to use Claude Code for Python development specifically. Each section is self-contained, so skip to whatever is relevant.
Why Claude Code for Python development
Python’s tooling ecosystem has a learning curve. You need a package manager, a virtual environment, a project configuration file, a test runner, a linter, and sometimes a type checker. For someone starting out, the gap between “I want to build something” and “I have a working project” can feel wide.
Claude Code compresses that gap. Tell it what you want to build and it can install the right tools, create the project structure, write the initial code, and run it (with your approval for each step). When it hits an error, it reads the traceback and proposes a fix without you needing to interpret the error message yourself.
This differs from editor-based copilots that autocomplete lines as you type. Claude Code operates at the project level: it creates files, installs packages, runs tests, and makes multi-file changes in a single request. It also differs from chat-based AI that can only suggest code you then copy-paste. Claude Code takes action directly in your terminal. You can use it alongside an editor; they serve different roles.
Installation
Claude Code runs in your terminal. Install it with the native installer:
# macOS / Linux
curl -fsSL https://claude.ai/install.sh | bash
# Windows (PowerShell)
irm https://claude.ai/install.ps1 | iexYou need a Claude Pro, Max, Teams, or Enterprise subscription, or an Anthropic API account with Console access. The first time you run claude in your terminal, it will walk you through authentication.
Important
Navigate to your project directory before launching. Claude Code reads the files in your current working directory to build context. Launching from your home directory means it will not know about your project.
cd my-project
claudeTo end a session, type /exit or press Ctrl+C.
Permissions and approvals
Claude Code asks for permission before taking actions that modify your system. When it wants to run a shell command, edit a file, or install a package, you see the proposed action and choose whether to allow it.
You can configure how much autonomy Claude Code has through permission rules and modes:
- Default mode: Claude Code prompts for approval on shell commands while allowing file edits. You can accept, reject, or modify each proposed action.
- Allowlists: You can mark specific tools or command patterns (like
uv run pytest) as always allowed, so Claude Code runs them without prompting. - Broader modes: Settings like
acceptEditsorbypassPermissionsreduce or eliminate prompts for experienced users who want faster iteration.
When Claude Code asks for approval, read the command or diff before confirming. This is your main safeguard against unintended changes.
Costs and token usage
Claude Code consumes resources with every interaction. API users pay per token; subscribers on Pro, Max, Teams, or Enterprise plans consume usage against their plan limits. Agentic workflows use resources quickly because each iteration through the build-run-fix cycle involves reading files, generating code, and processing command output.
- Check your usage. Type
/costin a session to see token consumption (most useful for API users). - Choose a model. Use
/modelto switch between available models. Smaller models use fewer resources and work well for straightforward tasks. - Keep sessions focused. A session that wanders across many unrelated tasks uses resources faster than necessary. Start a new session when you shift to a different task.
Slash commands
Claude Code has built-in commands that start with /. The most useful ones for daily work:
/helpshows all available commands./initgenerates aCLAUDE.mdfile for your project based on its structure./compactsummarizes the conversation to free up context space. See Context window limits for when to use this./costshows token usage for the current session./modelswitches between available Claude models./clearresets the conversation and starts fresh./exitends the session.
Setting up Python with Claude Code
Python does not need to be installed before starting. Ask Claude Code to handle it:
Install uv and create a new Python project called my-appClaude Code will install uv, which handles three things that trip up new Python developers:
Python versions. Python releases new versions regularly, and different projects may need different versions. uv downloads and manages Python interpreters so you don’t need to install Python from a website or wrestle with system package managers.
Virtual environments. A virtual environment keeps each project’s packages separate. Without one, installing a package for Project A can break Project B. When working with uv projects, commands like uv run and uv sync create and manage virtual environments automatically.
Packages. Python’s strength is its library ecosystem. uv installs packages faster than pip and tracks what your project depends on in a structured file. For a deeper look, see the Complete Guide to uv.
How to give good instructions
Claude Code works best when you say what you want concretely, not abstractly.
Weak: “Make this code better.”
Better: “This function is slow when the input list has more than 10,000 items. Find a faster approach.”
Weak: “Build me a web app.”
Better: “Create a FastAPI app with one endpoint, /greet, that takes a name query parameter and returns a JSON greeting.”
- State the goal, not just the task. “I’m building a CLI that processes CSV files” gives Claude Code context to make better decisions than “write a function that reads a CSV.”
- Mention constraints. “Use only the standard library” or “this needs to run on Python 3.10” prevents wasted iteration.
- Say what’s wrong instead of starting over. If Claude Code produces output that’s close but not right, describe the gap: “The output format is correct but the dates should be ISO 8601.”
The build-run-fix cycle
Software development is a loop: write code, run it, read the errors, fix them, run again. Claude Code automates this loop. It writes code, executes it, reads the traceback when something fails, edits the code, and reruns. You watch the cycle happen in your terminal.
Professional developers spend much of their time in this same loop. The difference is speed. Claude Code can go through several iterations in the time it would take to manually interpret an error message and look up the fix.
When to let it iterate:
- The errors are getting shorter or changing (progress is happening).
- It’s working through import errors, typos, or missing dependencies.
When to step in:
- It’s trying the same fix repeatedly.
- The approach seems wrong, not just the details. Say “stop” and redirect: “Try a different approach. Use X library instead.”
Context window limits
Claude Code holds the conversation in a context window. The size varies by model, but every context window has a limit. As a session grows longer, the context fills up. Claude Code auto-compacts when it approaches the limit, but quality can still degrade in long sessions as earlier details get summarized away.
Watch for these signs:
- Claude Code re-reads files it already examined.
- It suggests changes you already rejected.
- Responses become less relevant to your current task.
When this happens, use /compact to summarize the conversation history and reclaim context space. For a major topic change, start a fresh session with /clear or open a new terminal.
Tip
Short, focused sessions produce better results than marathon ones. If you are switching to a different task, start a new session.
Ask Claude Code to explain
You can ask Claude Code to explain anything it writes, at any time:
What does this function do?Walk me through how this project is structured and why.Explain the error handling in app.pyUse this freely. If you do not understand what the code does, you will struggle to maintain or debug it later. Claude Code can teach while it builds. Ask it to explain unfamiliar syntax, library choices, or design patterns as they come up.
Project structure
When Claude Code scaffolds a Python project intended to be imported as a library or package, it typically uses a src/ layout. The src/ directory prevents accidental imports from the project root during development. After running uv init --package, adding dependencies, and creating a test file, the structure looks like this:
- pyproject.toml
- uv.lock
- init.py
- main.py
- test_main.py
Tip
Running uv init without flags creates a simpler flat layout with main.py at the project root. The --package flag adds the src/ structure shown above. For a full comparison of the available layouts, see Understanding uv init project types.
pyproject.toml is the project’s configuration file. It lists the project name, Python version requirement, and direct dependencies. See Why choose pyproject.toml over requirements.txt? for background.
uv.lock is a lockfile that records the exact version of every dependency resolved for the project. This helps ensure reproducible installs across machines.
src/ contains your source code. The nested folder with __init__.py is a Python package.
tests/ contains automated tests. Keeping tests in a separate directory from source code is standard Python convention.
For a hands-on walkthrough, see the tutorial Create your first Python project.
Working with packages
Python’s library ecosystem is one of the language’s biggest strengths. When you need to make HTTP requests, parse dates, build a web server, or analyze data, there’s almost certainly a package for it.
Package names are not required upfront. Describe what you need:
I need to make HTTP requests to a REST API. Add the right package.Claude Code will choose an appropriate library (like httpx or requests), install it with uv add (after you approve), and use it in the code it writes. The dependency gets recorded in pyproject.toml so it’s tracked with the project.
To understand how dependency management works in detail, see the Complete Guide to uv.
CLAUDE.md: Standing instructions
A CLAUDE.md file in your project root gives Claude Code standing instructions it reads at the start of every session. For Python projects, this is the place to specify which tools to use, how to run tests, and any project conventions.
A realistic example:
# Project conventions
- Python >= 3.11
- Use uv for all package management (never pip)
- Use src/ layout (uv init --package)
- Run tests with: uv run pytest
- Run linting with: uv run ruff check .
- Format code with: uv run ruff format .
- Type check with: uv run ty check src/
## Code style
- Prefer httpx over requests for HTTP calls
- Use pathlib for file paths, not os.pathKeep CLAUDE.md short and factual. It should contain instructions that apply to every session, not one-time tasks. Commit it to version control so every collaborator gets the same behavior.
Tip
Run /init inside Claude Code to generate a starter CLAUDE.md based on your project’s structure. Then customize it with your conventions.
For a step-by-step setup, see How to configure Claude Code to use uv. For a comprehensive set of project scaffolding instructions you can paste into CLAUDE.md or into a Claude Code session, see the Modern Python Project Setup Guide for AI Assistants.
Testing
Automated tests are small programs that verify your code does what you expect. They run fast and catch mistakes before users do.
Ask Claude Code to write tests alongside your code:
Write tests for the parse_csv function in src/my_app/parser.pyOr ask it to add tests after the fact:
Add tests for the existing code in src/my_app/Claude Code will create test files, write test cases, and run them with pytest. A passing test suite looks like:
===== 5 passed in 0.12s =====A failing test shows you exactly what went wrong: what the code produced versus what was expected. Claude Code reads this output and can fix the code or the test depending on which is wrong.
Tests become valuable when making changes. Before modifying a function, ask Claude Code to run the test suite. A broken test tells you exactly what the change affected.
A productive pattern is test-driven development: ask Claude Code to write a failing test for the behavior you want, then ask it to make the test pass. This forces the implementation to match a concrete specification rather than a vague description.
Write a test that verifies parse_csv returns an empty list for an empty file. Then make the test pass.For a guided introduction, see the tutorial Setting up testing with pytest and uv.
Linting and formatting
A linter scans your code for common mistakes, style violations, and potential bugs. A formatter rewrites your code to follow consistent style rules (indentation, spacing, line length). Together, they keep code clean and readable.
Ruff handles both jobs. Ask Claude Code to set it up:
Add ruff to this project and configure it for linting and formattingOnce configured, you can ask Claude Code to check and fix your code:
Run ruff on the project and fix any issuesConsistent formatting helps when learning. It enforces uniform indentation and spacing across your codebase, making code easier to read and reducing style-related confusion.
For a full walkthrough, see the tutorial Set up Ruff for formatting and checking your code or the Complete Guide to Ruff.
Git integration
Claude Code understands git. It can read diffs, stage files, write commit messages, and create pull requests. For Python projects, this means you can ask it to handle version control as part of your workflow:
Commit these changes with a descriptive messageShow me what changed since the last commitCreate a pull request for this feature branchClaude Code reads the diff before writing a commit message, so the message reflects the actual changes rather than a generic summary. When creating pull requests, it can generate a description based on the commits in the branch.
Note
By default, Claude Code prompts for approval before running git commands that modify history or push to a remote. This depends on your permission configuration.
When Claude Code gets it wrong
Claude Code will write broken code, choose the wrong library, overcomplicate a solution, or misunderstand what you asked. This is expected.
Common footguns to watch for:
Warning
Always review the proposed command or diff before approving. This is where most mistakes are caught.
- Using
pip installinstead ofuv add. Without aCLAUDE.mdthat says otherwise, Claude Code may default to pip. Check the commands it proposes before approving. - Adding unnecessary dependencies. Claude Code sometimes pulls in a library for something the standard library handles. If you see an unfamiliar package in
uv add, ask why it’s needed. - Hallucinating library APIs. Claude Code may call functions or use parameters that don’t exist in the library version you’re using. If code fails with
AttributeErrororTypeErroron a library call, this is likely the cause. - Changing build configuration. It may change how your project is packaged, add tool sections to
pyproject.toml, or restructure your project in ways you didn’t ask for. Review diffs before approving. - Writing code that passes tests but is subtly wrong. Tests only catch what they test for. If Claude Code writes both the code and the tests, the tests may not cover edge cases. Read the implementation, not just the test results.
How to redirect:
- “Simplify this.” If the solution is more complex than it needs to be, say so directly. Claude Code tends toward over-engineering when the prompt is vague.
- “Try without that library.” If it pulled in a dependency you don’t want, tell it to use the standard library or a specific alternative.
- “That’s not what I meant. I want X, not Y.” Restate the requirement. Being specific about the gap between what you got and what you wanted is faster than starting over.
Always review the diff before approving changes. Your judgment is part of the process.
Debugging
When Python code fails, it produces a traceback: a stack of messages showing where the error occurred and what went wrong. Tracebacks follow a consistent format. The last line is the error type and message. The lines above show the chain of function calls that led to it.
When you encounter an error, share the context:
I ran the app and got this error. The traceback is below:
[paste the error]Or, if Claude Code ran the command itself, it already has the error output and will start diagnosing without you pasting anything.
Giving context about what changed helps narrow the problem:
This worked before I added the caching logic. The error started after that change.Claude Code handles common Python errors well: ImportError, TypeError, KeyError, missing dependencies, version mismatches. It reads the traceback, identifies the root cause, and proposes a fix.
Working with existing code
Claude Code can work with projects you didn’t create. Point it at an existing codebase and ask questions:
Explain the structure of this project. What are the main modules and how do they connect?What does the process_order function in orders.py do?When making changes to unfamiliar code, use tests as a safety net:
Run the existing tests, then change the date format in the report generator to ISO 8601If the project has tests, you can ask Claude Code to run them before and after the change. If a test breaks, it can identify the problem and propose a fix. If the project has no tests, ask Claude Code to add some for the code you’re about to modify.
Learn more
Handbook tutorials:
- Create your first Python project
- Set up Ruff for formatting and checking your code
- Setting up testing with pytest and uv
Handbook how-to guides:
Handbook complete guides:
Official documentation:
Get Python tooling updates
Subscribe to the newsletter