Getting Started· 20 min

Python Basics — a cheat sheet for every script

What you'll learn
  • Recognise every Python feature used in the course scripts
  • Read imports, dicts, f-strings, and type hints confidently
  • Understand argparse, dotenv, and the OpenAI client pattern
  • Know where to come back when a line of code looks unfamiliar

This is a one-page tour of every Python feature you will see in the course scripts. You do not need to memorise it — skim it now, and come back when a piece of code confuses you. Each topic maps directly to patterns you will meet in Session 1, 5, or 6.

Who is this for?
Students who know programming but have not touched Python in a while, or who have written Python but never used virtual environments, .env files, or modern type hints. If you are a total beginner, read through in order.

1. Imports — bringing code into your file

Python code lives in modules. You use "import" to pull in other modules or specific names from them.

imports.py
# Import a whole module and use it with the dotted name
import os
print(os.getenv("HOME"))

# Import a specific name from a module
from dotenv import load_dotenv
load_dotenv()

# Import multiple names at once
from openai import OpenAI
from pydantic import BaseModel, Field
The SDKs you use — openai, langchain_openai, pydantic, dotenv — are all just Python modules installed via pip. Nothing special.

2. Variables and types (no declaration needed)

variables.py
name = "Arya"          # string
age = 25                # integer
temperature = 0.7       # float
is_ready = True         # boolean (True / False — capitalised!)
nothing = None          # Python's "null"

# You can reassign to any type later
age = "twenty-five"     # legal — Python is dynamically typed

3. Strings and f-strings

f-strings (prefixed with f) let you embed expressions directly in a string with curly braces. You will see them everywhere in the course.

strings.py
city = "Bangkok"
temp = 32

# f-string — modern, clear
print(f"Weather in {city}: {temp}°C")

# Multi-line strings with triple quotes
prompt = f"""
You are a friendly tour guide.
Describe {city} in 3 sentences.
"""

# String methods you will use
"  hello  ".strip()     # "hello" — remove whitespace
"hello world".upper()   # "HELLO WORLD"
"hello".startswith("he")  # True

4. Lists, dicts, and tuples

The three everyday collection types. You will see dicts most often — they are what you build messages with.

collections.py
# List — ordered, mutable
cities = ["Bangkok", "Tokyo", "Paris"]
cities.append("Oslo")
print(cities[0])         # "Bangkok"
print(len(cities))       # 4

# Dict — key/value pairs, the shape of every OpenAI message
user_message = {"role": "user", "content": "Hello!"}
print(user_message["role"])        # "user"
user_message["content"] = "Hi!"    # update a value

# Tuple — ordered, immutable (usually for fixed pairs)
rgb = (255, 0, 0)
r, g, b = rgb            # unpacking
Messages are just lists of dicts
Every chat API call in this course is a list of dicts like [{"role": "system", "content": "..."}, {"role": "user", "content": "..."}]. Once you see that, the APIs stop feeling magical.

5. Functions and type hints

functions.py
# Simple function
def greet(name):
    return f"Hello, {name}!"

# With type hints (recommended — you will see these in course scripts)
def greet(name: str) -> str:
    return f"Hello, {name}!"

# Default argument values
def ask_model(prompt: str, temperature: float = 0.7) -> str:
    # ... call the API
    return "some answer"

# Calling
reply = ask_model("Hello")                   # uses default temperature
reply = ask_model("Hello", temperature=1.2)  # explicit keyword argument
Type hints are optional but helpful
Python does not enforce them at runtime, but VS Code uses them for autocomplete and Pylance will warn you if you pass the wrong type. Always write them.

6. if / elif / else and loops

control_flow.py
# if / elif / else — indentation matters!
score = 85
if score >= 90:
    grade = "A"
elif score >= 80:
    grade = "B"
else:
    grade = "C"

# for loop over a list
for city in ["Bangkok", "Tokyo", "Paris"]:
    print(city)

# for loop with index
for i, city in enumerate(cities):
    print(f"{i}: {city}")

# while loop (used for tool-call loops in Sessions 5 & 6)
done = False
while not done:
    # ... call the API, check if we need another round
    done = True

7. Classes and Pydantic models

Classes define custom types. Pydantic is a library for declaring "data shapes" used heavily in Sessions 5 and 6 for structured outputs.

classes.py
from pydantic import BaseModel

# A Pydantic model — declarative, with validation for free
class CalendarEvent(BaseModel):
    name: str
    date: str
    participants: list[str]

# Create an instance
event = CalendarEvent(
    name="Science Fair",
    date="2026-04-12",
    participants=["Alice", "Bob"],
)
print(event.name)           # "Science Fair"
print(event.participants)   # ["Alice", "Bob"]

# Turn into a dict
event.model_dump()          # {"name": "...", "date": "...", "participants": [...]}
You will define Pydantic models as the text_format= argument to the OpenAI SDK — the API then returns data that already matches your model.

8. argparse — handling --prompt and friends

argparse is Python's built-in library for parsing command-line arguments. Every script that takes --prompt, --image, or --topic uses it.

argparse_example.py
import argparse

# Build a parser
parser = argparse.ArgumentParser()
parser.add_argument("--prompt", required=True, help="Prompt to send")
parser.add_argument("--temperature", type=float, default=0.7)

# Parse whatever the user typed on the command line
args = parser.parse_args()

# Now use the values
print(args.prompt)       # string
print(args.temperature)  # float

# Run it like:
#   python script.py --prompt "Hello" --temperature 0.3
Free help flag
argparse auto-generates --help for you. Try running any course script with --help to see its arguments.

9. Environment variables and .env files

You never paste API keys into source code. Instead you put them in a .env file and load them with python-dotenv. os.getenv() reads the resulting values.

env_vars.py
import os
from dotenv import load_dotenv

# Read .env into process environment variables
load_dotenv()

# Get a value (returns None if missing — always check!)
api_key = os.getenv("OPENAI_API_KEY")
if not api_key:
    raise SystemExit("Set OPENAI_API_KEY in .env")

# Optional with a default
model = os.getenv("OPENAI_MODEL", "gpt-4o-mini")

10. The if __name__ == "__main__" idiom

Every script in the course ends with this block. It means: "only run main() when this file is executed directly, not when it is imported by another script."

main_guard.py
def main() -> None:
    print("Doing the work...")

if __name__ == "__main__":
    main()
You can ignore this line and your code still runs. It just becomes important once you start writing shared helpers in common.py that you import from other scripts.

11. Error handling with try / except

errors.py
try:
    response = client.responses.create(model=model, input=args.prompt)
    print(response.output_text)
except Exception as e:
    print(f"API call failed: {e}")
    # optionally: raise  (re-raises after logging)
Catch specific errors in production
In workshop scripts we often catch the broad Exception for simplicity. In real apps catch specific ones like openai.RateLimitError or openai.APIConnectionError.

12. Working with files and paths

files.py
from pathlib import Path

# Read a text file
text = Path("notes.txt").read_text()

# Write bytes to a file (used for image / audio output)
import base64
png_bytes = base64.b64decode(b64_string)
Path("output/generated.png").write_bytes(png_bytes)

# Make sure a folder exists
Path("output").mkdir(parents=True, exist_ok=True)

13. Working with JSON

json_example.py
import json

# Parse a JSON string into a Python dict
raw = '{"name": "Arya", "age": 25}'
data = json.loads(raw)
print(data["name"])

# Convert a Python dict back into a JSON string (pretty-printed)
text = json.dumps(data, indent=2)

# Save to a file
Path("output/data.json").write_text(json.dumps(data, indent=2))

14. The OpenAI client — the pattern you will memorise

openai_pattern.py
from dotenv import load_dotenv
from openai import OpenAI

load_dotenv()                                  # 1. load .env
client = OpenAI()                              # 2. create client (uses OPENAI_API_KEY automatically)

response = client.responses.create(            # 3. call the API
    model="gpt-4o-mini",
    input="Hello!",
)

print(response.output_text)                    # 4. read the reply
This is 90% of Session 1
Every Session 1 exercise is a variation of this pattern — different input shapes, different model parameters, or different endpoints (images.generate, audio.speech.create). Once this pattern is in your head, everything else is a tweak.

15. The LangChain pattern (Session 6)

langchain_pattern.py
from langchain_openai import ChatOpenAI

llm = ChatOpenAI(model="gpt-4o-mini", temperature=0.3)

# Same code works with ChatAnthropic or ChatGoogleGenerativeAI
result = llm.invoke("Hello!")
print(result.content)

Quick reference — commands inside .venv

Cheat sheet
# See Python version
python --version

# Install a library
pip install openai

# See everything installed
pip list

# Run a script
python src/01_text_basic.py --prompt "..."

# Get help for any script that uses argparse
python src/01_text_basic.py --help

# Start an interactive Python session (great for experimenting)
python
That is the whole vocabulary
If you understand the 15 sections above, every script in Session 1, 5, and 6 will read like English. Come back to this page whenever a line in a script looks unfamiliar.