Python Basics — a cheat sheet for every script
- ▸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.
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.
# 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, Field2. Variables and types (no declaration needed)
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 typed3. 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.
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") # True4. Lists, dicts, and tuples
The three everyday collection types. You will see dicts most often — they are what you build messages with.
# 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 # unpacking5. Functions and type hints
# 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 argument6. if / elif / else and loops
# 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 = True7. 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.
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": [...]}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.
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.39. 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.
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."
def main() -> None:
print("Doing the work...")
if __name__ == "__main__":
main()11. Error handling with try / except
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)12. Working with files and paths
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
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
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 reply15. The LangChain pattern (Session 6)
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
# 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