Python AI Learning Guide
Python AI Learning Guide
AI
Connection How each Python concept powers real AI automation workflows
Goal Equip you to read, write, and automate AI-powered Python scripts
Python for AI Automation Page 2
Table of Contents
Topic 1 — Creating Variables
Storing, naming, and using data in Python
Topic 2 — Expressions
Calculations, comparisons, and logical operations
Topic 4 — Functions
Reusable blocks of code — the building blocks of AI
Topic 6 — Strings
Working with text — the language of AI prompts
Topic 7 — Files
Reading and writing data from disk
Topic 8 — Lists
Ordered collections of data
Topic 9 — Dictionaries
Key-value stores — the structure of AI responses
Topic 10 — Tuples
Immutable sequences for safe data handling
■ Every topic includes a dedicated AI Automation section showing exactly how that concept is used in real AI, machine
learning, and automation projects.
This guide covers the ten foundational Python concepts that every AI practitioner uses daily. For each topic you will learn
what it is, how to use it with practical code examples, why it matters, and crucially — how it connects to AI automation.
INSTALL Install Python: go to [Link]/downloads and download the latest version. Install a code editor
like VS Code (free). To install any library, open a terminal and type: pip install library-name
TOPIC 1
Creating Variables
A variable is a named storage container for data. Think of it as a labelled box — you put something inside, give the box a
name, and refer to that name whenever you need the contents. In Python, you create a variable simply by writing a name,
an equals sign, and a value. There is no need to declare a type first — Python figures it out.
print(type(name)) #
print(type(age)) #
x, y, z = 10, 20, 30
score = 0
API_BASE_URL = '[Link]
Every AI script you will ever write relies on variables. Your OpenAI API key lives in a variable. The prompt you
send to ChatGPT is stored in a variable. The AI's response text gets assigned to a variable. Configuration
values like model name, max_tokens, and temperature are stored as constants. Without variables, you
cannot store the AI's output, pass data between steps, or build any automation logic. Real example — calling
an AI API: api_key = 'sk-...' | model = 'gpt-4' | response = [Link](...) | answer =
[Link][0].[Link]
Storing API keys Keep your OpenAI/Anthropic key in a variable (or env variable) to authenticate
requests
Tracking state message_count, tokens_used, session_id track what has happened across AI
calls
Dynamic prompts user_name and topic variables get inserted into prompt templates at runtime
TOPIC 2
Expressions
An expression is any piece of code that produces a value. When Python evaluates an expression, it computes a result.
Expressions include arithmetic calculations, string operations, comparisons between values, and logical combinations.
Understanding expressions lets you compute results, validate data, and make decisions in your programs.
Arithmetic Expressions
# Arithmetic operators
tokens_used = 3500
cost_per_1k = 0.002
# Comparing strings
status = 'active'
Logical Expressions
# Logical operators: and, or, not
age = 25
has_account = True
name = 'Claude'
# Expression in an f-string
tokens = 1500
Expressions are the calculations that drive AI automation logic. You use arithmetic expressions to calculate
token costs and API rate limits. Comparison expressions check whether a confidence score is above a
threshold before acting on an AI prediction. Logical expressions combine multiple conditions: 'if the response
is not None AND the status code is 200 AND the content is not empty'. F-string expressions are used
constantly to build dynamic prompts by embedding variable values into prompt text at runtime.
Confidence thresholds is_confident = score >= 0.85 — only act on AI predictions above 85% confidence
Rate limit checking can_call = requests_this_minute < 60 and tokens_this_hour < 90000
Validating AI output is_valid = len(response) > 0 and response != 'None' — check before processing
TOPIC 3
Conditional Execution (if statements)
Conditional execution lets your program make decisions. Based on whether a condition is True or False, your code takes
different paths — just like a human deciding what to do based on a situation. The if statement is the gateway to intelligent
behavior in code. Without it, programs would just blindly execute the same steps regardless of what is happening.
temperature = 38.5
score = 72
result = 'Pass'
else:
result = 'Fail'
api_status_code = 429
if api_status_code == 200:
else:
user_role = 'admin'
is_verified = True
if user_role == 'admin':
if is_verified:
else:
else:
requested_model = 'gpt-4'
if requested_model in allowed_models:
else:
Every AI automation workflow is full of conditionals. When you call an AI API, you check: did the call
succeed? Is the response what we expected? Does the confidence score meet the threshold? Should we
retry? Conditionals let your AI script handle errors gracefully, route different types of user input to different AI
models, stop processing if the AI returns an unexpected result, and implement fallback behavior when an API
call fails. They are the difference between a fragile script and a robust AI automation pipeline.
API error handling if response.status_code != 200: retry or raise an error with a helpful message
Model routing if task == 'image': use DALL-E; elif task == 'code': use GPT-4; else: use Claude
Content moderation if ai_safety_score > 0.8: block the content; else: allow and log it
Retry logic if error_type == 'rate_limit': wait 60 seconds and retry the API call
Threshold-based actions if sentiment_score < -0.5: trigger an alert and escalate to human review
TOPIC 4
Functions
A function is a named, reusable block of code that performs a specific task. Instead of writing the same 20 lines over and
over, you define the steps once in a function and call it by name whenever needed. Functions are the primary building block
of all software — including AI systems. They accept inputs (parameters), process them, and return an output (return
value).
def greet(name):
return message
print(result)
print(f'Response: {response[:100]}...')
def parse_ai_response(raw):
text = [Link][0].[Link]
tokens = [Link].total_tokens
"""
Parameters:
"""
client = [Link]()
response = [Link](
model=model,
max_tokens=max_tokens,
temperature=temperature
return [Link][0].[Link]
Functions are the architecture of AI automation. Every well-built AI script wraps each concern in a function:
one function to call the AI API, one to parse the response, one to validate the output, one to save results to a
file. This makes your code reusable, testable, and maintainable. AI libraries like LangChain and Hugging
Face are built entirely from functions and classes. When you build an AI agent — a system that takes actions
autonomously — each tool the agent can use is defined as a Python function.
API wrapper function def call_claude(prompt): wraps the full Anthropic API call in a reusable, clean
interface
Prompt templates def build_prompt(topic, tone, length): builds consistent prompts from parameters
Response parsers def extract_json(response_text): reliably extracts structured data from AI output
Retry with backoff def call_with_retry(prompt, max_retries=3): retries failed API calls automatically
AI tool definitions Functions are literally how you give tools to AI agents (function calling / tool use)
Batch processing def process_batch(items): loops through items calling the AI function for each one
TOPIC 5
Loops and Iteration
Loops let you repeat a block of code automatically — either a fixed number of times or until a condition is met. This is one of
the most powerful concepts in programming. Without loops, you would have to copy and paste the same code hundreds of
times to process hundreds of items. With loops, you write the logic once and let Python repeat it over an entire dataset, list of
files, or batch of API requests.
print(f'Processing: {fruit}')
print(f'Attempt {i+1}')
print(n)
prompts = [
results = []
[Link](response)
print(f'Done: {prompt[:40]}...')
attempts = 0
max_attempts = 3
success = False
attempts += 1
print(f'Attempt {attempts}...')
success = True
else:
if item is None:
process(item)
Loops are the engine of AI automation. They let you process hundreds of documents through an AI model
automatically, retry failed API calls, stream through a conversation history, parse every item in a dataset, and
build batch processing pipelines. A loop over a list of customer emails combined with an AI summarization
function can process an entire inbox in seconds. Loops are also essential for training ML models — the
training loop adjusts model weights repeatedly until the model's predictions improve.
Batch document processing for doc in documents: summary = summarize_with_ai(doc) — process 1000 docs
overnight
Conversation loops while user_input != 'quit': get input, call AI, print response — build a chatbot REPL
Retry with exponential while retries < max: try API call; on failure: sleep(2**retries); retries += 1
backoff
Dataset labeling for row in csv_data: label = classify_with_ai(row['text']) — auto-label training data
Web scraping + AI for url in url_list: page = scrape(url); summary = ask_ai(page) — summarize
websites
Training ML models for epoch in range(100): [Link](batch); loss = evaluate() — the ML training
loop
TOPIC 6
Strings
A string is a sequence of characters — text. Since AI models communicate entirely through text (prompts in, text out),
strings are arguably the most important data type for AI automation. You need strings to build prompts, clean AI responses,
extract specific information from text, format output for users, and interact with text-based APIs.
single = 'Hello'
double = "World"
multi = '''This is a
multi-line string
word = 'Python'
# Cleaning
# Searching
[Link]('He') # True
[Link]('!') # True
sentence = 'apple,banana,cherry'
length = 3
clean = [Link]().rstrip('.')
Strings ARE the AI interface. Every prompt you send to an AI model is a string. Every response you receive is
a string. The entire craft of 'prompt engineering' is the art of constructing the right string to get the best AI
output. You will use string methods to clean messy AI responses, split structured outputs, check if the AI
returned what you expected, build dynamic prompts from templates, and format results for users or
downstream systems. Multi-line strings (triple quotes) are perfect for writing long, detailed system prompts.
Prompt engineering f-strings let you build dynamic prompts: f'Translate this to {language}: {text}'
Text chunking for AI Split long documents into chunks that fit within token limits
System prompt templates Triple-quoted strings hold multi-paragraph system prompts with clear formatting
TOPIC 7
Files
Working with files lets your Python programs read data from disk and write results back. In AI automation, this means
reading documents to feed to an AI model, saving AI-generated content, logging API responses for later analysis, reading
configuration files, and building data pipelines that ingest and output files automatically.
Reading Files
# Always use 'with' — it closes the file automatically
content = [Link]()
for line in f:
print(line)
import csv
print(row['name'], row['email'])
Writing Files
# Write (creates file or OVERWRITES existing)
[Link]('Second line\n')
import json
data = {'prompt': 'Explain AI', 'response': 'AI stands for...', 'tokens': 142}
loaded = [Link](f)
import os
if [Link]('.txt'):
with open(f'documents/{filename}') as f:
text = [Link]()
[Link](summary)
Files are the input and output of most real-world AI automation pipelines. You read text files or PDFs to
create the content you send to an AI. You write the AI's responses to files for later use. JSON files are
particularly important because AI APIs return JSON responses, and you often store prompts, responses, and
metadata in JSON format. Environment files (.env) store API keys securely. Log files record every AI
interaction for debugging and auditing. File handling lets you build pipelines that process thousands of
documents automatically overnight.
Document AI pipeline Read 500 .txt files, send each to Claude for summarization, write results to new
files
API response logging Append each prompt+response pair to a JSONL log file for analysis and
debugging
Config files Read model settings from [Link] so you can change behavior without editing
code
Training data creation Write AI-generated examples to CSV files to create datasets for ML model
training
Environment variables Load API keys from .env file using python-dotenv — never hardcode keys in code
Batch report generation For each customer in [Link], generate a personalized AI report and save
as PDF
TOPIC 8
Lists
A list is an ordered, changeable collection of items. Lists can hold any type of data — numbers, strings, other lists, or even
AI response objects. They are the most commonly used data structure in Python and are essential for holding batches of
prompts, storing conversation history, collecting AI responses, and managing sequences of data through a processing
pipeline.
# Access by index
# Adding items
# Removing items
conversation = []
def chat(user_message):
response = [Link](
model='gpt-4',
messages=conversation
ai_message = [Link][0].[Link]
return ai_message
Lists are the containers that hold your AI pipeline together. Conversation history is a list of message
dictionaries — without this list, every AI turn would forget the entire previous conversation. Batch processing
sends a list of prompts through a loop. AI model outputs like classification labels, detected entities, and
generated options come back as lists. Embeddings (numerical representations of text used in semantic
search and RAG systems) are lists of floating-point numbers. The entire concept of a dataset — thousands of
text samples for training — is a list of lists.
Conversation memory conversation = [] stores the full chat history sent to the AI on every turn
AI model outputs labels = ['positive', 'neutral', 'negative'] — possible classes for text classification
Embeddings embedding = [0.023, -0.415, 0.881, ...] — a list of 1536 floats representing
meaning
RAG document chunks chunks = split_document(text, 500) — list of text chunks for retrieval-augmented
gen
TOPIC 9
Dictionaries
A dictionary stores data as key-value pairs — like a real dictionary where each word (key) has a definition (value).
Dictionaries let you look up any value instantly by its key, without searching through the entire structure. They are the most
important data structure for working with AI APIs, because AI responses, API request bodies, JSON data, and configuration
settings are all dictionaries.
person = {
'name': 'Alice',
'age': 28,
person['name'] # 'Alice'
# Remove a key
del person['age']
print(f'{key}: {value}')
request_body = {
'model': 'claude-3-opus-20240229',
'max_tokens': 1024,
'messages': [
response = {
'id': 'msg_01XFDUDYJgAACzvnptvVoYEL',
'model': 'claude-3-opus-20240229',
answer = response['content'][0]['text']
tokens_in = response['usage']['input_tokens']
tokens_out = response['usage']['output_tokens']
cache = {}
def cached_ai(prompt):
if prompt in cache:
result = ask_ai(prompt)
return result
Dictionaries ARE the language of AI APIs. Every request you send to OpenAI, Anthropic, or any AI service is
a dictionary serialized to JSON. Every response you receive is a JSON object parsed back into a dictionary.
Understanding dictionaries means understanding how to build API requests correctly and extract exactly what
you need from responses. They are also used to store model configurations, build prompt libraries (name ->
template), cache expensive AI results, store entity extraction results, and represent structured data extracted
from text by AI.
API request bodies {'model': 'gpt-4', 'messages': [...], 'temperature': 0.7} — the exact format APIs
expect
Prompt libraries prompts = {'summarize': '...', 'translate': '...', 'classify': '...'} — reusable templates
AI response caching cache = {} stores previous AI calls so identical prompts don't waste API credits
Entity extraction {'person': 'Alice', 'company': 'OpenAI', 'date': '2024'} — structured AI output
Model configuration config = {'model': 'gpt-4', 'temp': 0.3, 'max_tokens': 500} — easy to swap settings
TOPIC
10 Tuples
A tuple is like a list — it holds an ordered sequence of items — but it is immutable: once created, its contents cannot be
changed. This makes tuples perfect for data that should never be modified: coordinates, configuration pairs, function return
values with multiple outputs, and constant lookup tables. Immutability is a safety guarantee that prevents accidental changes
to critical data.
point[0] # 10
point[1] # 20
def get_model_stats(model_name):
AI_MODELS = (
Use when Data that changes Data that must not change
Tuples provide safety and clarity in AI code. Use tuples to define the list of available AI models and their
properties — since this should never change at runtime. Use tuple unpacking to cleanly receive multiple
return values from AI helper functions (text, token_count, finish_reason = parse_response(raw)). Coordinate
tuples represent positions in image processing AI tasks. Named tuples (from the collections module) create
lightweight, readable objects for holding AI response metadata without defining a full class. Tuples can also
be used as dictionary keys — handy for caching AI results keyed by (model, prompt) pairs.
Model constant tables AI_MODELS = (('gpt-4', 8192, 0.03), ...) — immutable reference of available
models
Multi-value function returns text, tokens, reason = call_ai(prompt) — clean unpacking of AI response data
Cache keys cache[(model_name, prompt)] = response — tuples as compound dict keys for
caching
Image AI coordinates bounding_box = (x1, y1, x2, y2) — pixel coordinates from object detection models
MODEL = 'gpt-4'
MAX_TOKENS = 500
INPUT_FOLDER = 'documents/'
OUTPUT_FILE = '[Link]'
results = {}
client = [Link]()
response = [Link](
model=MODEL,
max_tokens=MAX_TOKENS
text_out = [Link][0].[Link]
tokens = [Link].total_tokens
def process_folder(folder):
total_tokens = 0
content = [Link]()
if len([Link]()) == 0:
continue
word_count = len([Link]())
style = 'bullet-point'
style = 'concise'
else:
style = 'one-sentence'
total_tokens += tokens_used
results[filename] = {
'summary': summary,
'word_count': word_count,
'tokens_used': tokens_used,
'style': style
return total_tokens
total = process_folder(INPUT_FOLDER)
[Link](results, f, indent=2)
Phase 1 (You
Python Fundamentals All 10 topics in this guide — the foundation of everything
are here)
Phase 3 APIs & HTTP requests library, REST APIs, JSON — talk to any web service
Phase 6 LangChain / LlamaIndex Chains, agents, RAG, memory — build complex AI workflows
FINAL TIP The fastest way to learn is to build something you care about. Pick a task you do repeatedly —
summarizing emails, researching topics, generating reports — and automate it with Python and
an AI API. You will use all 10 topics in this guide within the first script you write.