Skip to main content
Note: This is a quick-reference Python guide focused on AI/ML workflows. For a comprehensive Python course, see our Complete Python Crash Course.

Getting Started

1. Install Python

Download Python 3.11+ from python.org. Verify installation:

2. Set Up Virtual Environment

Virtual environments are like separate toolboxes for each project. Without them, installing a package for Project A might break Project B because they need different versions of the same library. This is not a theoretical concern — it will happen to you within your first week of AI development, because LLM libraries update frequently and often have conflicting dependencies.

3. Install AI Packages

4. Manage Dependencies


Python Core Syntax (AI Context)

These are the Python fundamentals you will use daily in AI engineering. We focus on what matters for working with LLM APIs, data processing, and async workflows — not the full breadth of Python.

Variables & Types

Functions

Control Flow

Error Handling

Error handling is not optional in AI engineering — LLM APIs fail regularly due to rate limits, network issues, and content policy violations. Every API call should be wrapped in try/except. The pattern below catches errors from most specific to most general, which is important because Python matches the first except block that fits.

Data Structures for AI

Working with JSON

JSON is the lingua franca of LLM APIs. Every request you send is JSON, every response you receive is JSON, and structured outputs are JSON. Mastering json.loads() and json.dumps() is as fundamental to AI engineering as knowing how to read and write.

List Operations

Dictionary Operations


Object-Oriented Python for AI

Classes & Dataclasses

Why dataclasses? Reduces boilerplate for data objects. Perfect for API responses, configuration objects, and structured data.

Type Hints (Modern Python)

Why type hints? Better IDE support, catch bugs early, and self-documenting code.

Dependency Management: pip vs. Poetry vs. uv

Choosing the right tool for managing Python packages will save you hours of debugging dependency conflicts — a common occurrence in AI projects because libraries like langchain, transformers, and torch have deep and sometimes conflicting dependency trees. AI-specific recommendation: For AI projects that need PyTorch or CUDA, start with uv (fast, modern) and fall back to conda only if you need binary packages that pip cannot install (e.g., specific CUDA toolkit versions). For everything else, uv or pip-tools gives you speed and reproducibility.

Advanced Patterns for AI Engineering

Decorators (Reusable Logic)

Decorators are functions that wrap other functions to add behavior — think of them as “middleware for functions.” They are everywhere in AI engineering: @retry for handling flaky API calls, @timer for profiling, @cache for avoiding redundant LLM calls, and @observe for tracing. If you understand decorators, you can read (and write) production AI code. If you do not, they will look like magic.
Use cases:
  • @timer - Profile slow functions
  • @retry - Handle flaky API calls
  • @cache_result - Avoid redundant LLM calls

Context Managers (Resource Management)

Context managers ensure resources are properly managed—files closed, connections released, timers stopped.
Use cases:
  • File I/O
  • Database connections
  • Timing code blocks
  • Temporary state changes

Async/Await (Concurrency)

Async is the single most important advanced Python pattern for AI engineering. Here is why: a typical LLM API call takes 1-5 seconds, and during that time your program is just waiting for a network response. Without async, processing 10 prompts takes 10-50 seconds. With async, all 10 run concurrently and you get results in 1-5 seconds total. That is a 10x speedup for free. The mental model: async def declares a function that can pause (at await points) and let other tasks run while it waits. asyncio.gather runs multiple async tasks concurrently.
Why async? Process multiple API calls concurrently. 10 sequential 1-second calls = 10 seconds. 10 concurrent = ~1 second. For batch processing, this is not a nice-to-have — it is the difference between a feature that ships and one that times out.

File Operations


Environment Variables (.env)

API keys are the crown jewels of your AI application. A leaked OpenAI key can rack up thousands of dollars in charges before you notice. The .env pattern keeps secrets out of your code and out of git history. This is not a suggestion — it is a hard requirement for any project that will ever be shared, deployed, or committed to a repository.
.env file:
Never commit .env files! Add .env to your .gitignore immediately when you create a new project — before you make your first commit. If you accidentally commit a key, rotate it immediately; removing it from git history is difficult and unreliable.

Essential Libraries for AI

HTTP Requests

Data Manipulation (Pandas)

Date & Time


Common AI Patterns

These patterns appear in virtually every AI application. They are worth memorizing because you will use them dozens of times.

Loading Environment Variables

Building Prompts

Batching Requests

Batching is essential when you have hundreds or thousands of items to process. Sending them all at once will hit rate limits; sending them one at a time is painfully slow. Batching gives you the best of both worlds: controlled throughput that stays within API limits while processing efficiently. The yield keyword makes this a generator, which means it processes one batch at a time and does not load all results into memory.

Rate Limiting

OpenAI, Anthropic, and other providers enforce rate limits (typically measured in requests per minute and tokens per minute). Exceeding them results in 429 errors and temporary bans. This simple rate limiter adds a fixed delay between calls to keep you under the limit. For production use, consider the tenacity library for more sophisticated retry-with-backoff patterns.

Sync vs. Async: When to Use What

Edge case — mixing sync and async: If you call a sync function (like requests.get()) from inside an async function, it blocks the entire event loop. Use httpx (async HTTP) instead of requests, or wrap sync calls in asyncio.to_thread() to run them in a thread pool without blocking.

Next Steps

Next Steps


Quick Reference

Common Commands

Style Guidelines (PEP 8)

Type Hints Quick Reference


Common Python Gotchas in AI Work

These are the mistakes that burn hours of debugging time specifically in AI engineering contexts:

Troubleshooting

”Module not found” error

”pip: command not found”

Import errors in VS Code

  1. Select correct Python interpreter: Ctrl+Shift+P → “Python: Select Interpreter”
  2. Choose the one in your venv folder

Slow pip installs


Pro Tips:
  • Use virtual environments for EVERY project
  • Pin package versions in production (package==1.2.3)
  • Use type hints—they catch bugs before runtime
  • Learn list/dict comprehensions—they’re faster and more Pythonic
  • Use python-dotenv for API keys and secrets