0% found this document useful (0 votes)
3 views31 pages

Python AI Learning Guide

This document is a comprehensive guide for beginners to learn Python fundamentals with a focus on AI automation. It covers ten core topics essential for AI practitioners, including variables, expressions, conditional execution, and functions, while demonstrating their application in AI workflows. The guide emphasizes Python's readability and its importance in building AI systems, providing practical examples and use cases throughout.

Uploaded by

hashimmuzahuura
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views31 pages

Python AI Learning Guide

This document is a comprehensive guide for beginners to learn Python fundamentals with a focus on AI automation. It covers ten core topics essential for AI practitioners, including variables, expressions, conditional execution, and functions, while demonstrating their application in AI workflows. The guide emphasizes Python's readability and its importance in building AI systems, providing practical examples and use cases throughout.

Uploaded by

hashimmuzahuura
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Python

Fundamentals & AI Automation


A Complete Learning Guide for Beginners to AI Practitioners

10 Core Variables, Expressions, Conditions, Functions, Loops, Strings, Files, Lists,


Topics Dictionaries, Tuples

AI
Connection How each Python concept powers real AI automation workflows

Level Absolute beginner — no prior programming knowledge required

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 3 — Conditional Execution (if)


Making decisions and branching logic

Topic 4 — Functions
Reusable blocks of code — the building blocks of AI

Topic 5 — Loops and Iteration


Repeating tasks automatically over data

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.

Python Fundamentals & AI Automation Guide


Python for AI Automation Page 3

Introduction: Why Python? Why Now?


Python is the world's most popular programming language for artificial intelligence, machine learning, data science, and
automation. It was designed to be readable — it looks almost like plain English — which means you spend your time solving
problems rather than wrestling with complex syntax. Whether you want to build a chatbot, automate repetitive office tasks,
analyze data, or interact with AI APIs like OpenAI's GPT or Google Gemini, Python is your starting point.

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.

The Python Ecosystem for AI


Library What It Does

openai Call ChatGPT, GPT-4, DALL-E APIs from Python

anthropic Call Claude AI models from Python

langchain Build chains of AI calls, memory, agents

transformers Run open-source AI models (Hugging Face)

pandas Manipulate and analyze data in tables

numpy Fast numerical computation for ML

scikit-learn Classical machine learning algorithms

requests Make HTTP calls to any web API

beautifulsoup4 Scrape and parse web pages

playwright Automate browsers with Python

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

Python Fundamentals & AI Automation Guide


Python for AI Automation Page 4

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.

How to Create Variables


# Basic variable assignment

name = 'Alice' # String (text)

age = 28 # Integer (whole number)

salary = 72500.50 # Float (decimal number)

is_employed = True # Boolean (True or False)

# Python detects the type automatically

print(type(name)) #

print(type(age)) #

# Multiple assignment in one line

x, y, z = 10, 20, 30

# Reassigning a variable (the box gets new contents)

score = 0

score = 100 # Now score holds 100

# Constants (by convention, use ALL_CAPS)

MAX_TOKENS = 4096 # Won't change during runtime

API_BASE_URL = '[Link]

Variable Naming Rules


• Must start with a letter or underscore: user_name, _private
• Can contain letters, numbers, and underscores: response_1
• Cannot start with a number: 1value is invalid
• Case-sensitive: Name and name are two different variables
• Use lowercase with underscores (snake_case) by Python convention: user_prompt

Python Data Types Overview


Type Example Used For

str 'Hello AI' Text, prompts, API keys, file paths

int 42 Counts, indices, token limits, iterations

Python Fundamentals & AI Automation Guide


Python for AI Automation Page 5

float 0.95 Confidence scores, percentages, temperatures

bool True / False Flags, on/off switches, filter conditions

NoneType None Representing 'no value yet', uninitialized state

■ AI AUTOMATION: Variables in AI Automation

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]

Use Case How This Topic Helps

Storing API keys Keep your OpenAI/Anthropic key in a variable (or env variable) to authenticate
requests

Saving AI responses ai_response = [Link](...) stores the full response object

Config management MAX_TOKENS, TEMPERATURE, MODEL_NAME constants control AI behavior


without editing code

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

Python Fundamentals & AI Automation Guide


Python for AI Automation Page 6

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

total = 100 + 250 # Addition -> 350

remaining = 500 - 120 # Subtraction -> 380

area = 12 * 8 # Multiplication -> 96

ratio = 22 / 7 # Division -> 3.142... (always float)

whole = 22 // 7 # Floor division -> 3 (integer result)

leftover = 22 % 7 # Modulo -> 1 (remainder)

squared = 2 ** 10 # Exponentiation -> 1024

# Order of operations follows PEMDAS — use parentheses to be explicit

result = (100 + 50) * 0.1 # -> 15.0 (NOT 100 + 5.0)

# Useful for AI: calculate cost from token usage

tokens_used = 3500

cost_per_1k = 0.002

total_cost = (tokens_used / 1000) * cost_per_1k # -> 0.007

Comparison Expressions (return True or False)


# Comparison operators

5 > 3 # True — greater than

5 < 3 # False — less than

5 >= 5 # True — greater than or equal

5 <= 4 # False — less than or equal

5 == 5 # True — equal to (note: double ==, not single =)

5 != 3 # True — not equal to

# Comparing strings

status = 'active'

status == 'active' # True

status != 'banned' # True

Python Fundamentals & AI Automation Guide


Python for AI Automation Page 7

Logical Expressions
# Logical operators: and, or, not

age = 25

has_account = True

# 'and' — BOTH conditions must be True

can_access = age >= 18 and has_account # True

# 'or' — AT LEAST ONE condition must be True

is_vip = age > 60 or has_account # True

# 'not' — reverses True/False

is_blocked = not has_account # False

# String expressions — f-strings (formatted strings)

name = 'Claude'

greeting = f'Hello, {name}! You are an AI assistant.'

# -> 'Hello, Claude! You are an AI assistant.'

# Expression in an f-string

tokens = 1500

msg = f'Used {tokens} tokens. Cost: ${tokens/1000 * 0.002:.4f}'

■ AI AUTOMATION: Expressions in AI Automation

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.

Use Case How This Topic Helps

Token cost calculation total_cost = (prompt_tokens + completion_tokens) / 1000 * price_per_1k

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

Building AI prompts prompt = f'Summarize this article in {word_limit} words: {article_text}'

Validating AI output is_valid = len(response) > 0 and response != 'None' — check before processing

Python Fundamentals & AI Automation Guide


Python for AI Automation Page 8

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.

Basic if / elif / else Structure


# Basic if statement

temperature = 38.5

if temperature > 37.5:

print('Fever detected — alert the system') # runs if True

# if / else — two possible paths

score = 72

if score >= 60:

result = 'Pass'

else:

result = 'Fail'

# if / elif / else — multiple paths

api_status_code = 429

if api_status_code == 200:

print('Success — process the response')

elif api_status_code == 429:

print('Rate limit hit — wait and retry')

elif api_status_code == 401:

print('Authentication failed — check API key')

elif api_status_code == 500:

print('Server error — try again later')

else:

print(f'Unexpected status: {api_status_code}')

Nested Conditions and In Operator


# Nested if statements

user_role = 'admin'

is_verified = True

Python Fundamentals & AI Automation Guide


Python for AI Automation Page 9

if user_role == 'admin':

if is_verified:

print('Full access granted')

else:

print('Admin account not verified')

else:

print('Standard access only')

# The 'in' operator — check membership

allowed_models = ['gpt-4', 'gpt-3.5-turbo', 'claude-3-opus']

requested_model = 'gpt-4'

if requested_model in allowed_models:

print(f'Sending request to {requested_model}')

else:

print('Model not supported')

# One-line conditional (ternary expression)

label = 'Positive' if score > 0.5 else 'Negative'

■ AI AUTOMATION: Conditional Execution in AI Automation

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.

Use Case How This Topic Helps

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

Prompt customization if user_language == 'es': prepend 'Responde en espanol:' to every prompt

Python Fundamentals & AI Automation Guide


Python for AI Automation Page 10

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).

Defining and Calling Functions


# Define a function with 'def'

def greet(name):

message = f'Hello, {name}!'

return message

# Call the function

result = greet('Alice') # -> 'Hello, Alice!'

print(result)

# Function with multiple parameters

def calculate_cost(tokens, price_per_1k=0.002):

"""Calculate API cost from token count."""

return (tokens / 1000) * price_per_1k

cost = calculate_cost(3500) # uses default price

cost2 = calculate_cost(3500, 0.006) # overrides default

# Function with no return (performs an action)

def log_response(prompt, response, model):

print(f'[{model}] Prompt: {prompt[:50]}...')

print(f'Response: {response[:100]}...')

# Functions can return multiple values

def parse_ai_response(raw):

text = [Link][0].[Link]

tokens = [Link].total_tokens

return text, tokens

answer, usage = parse_ai_response(response)

Functions That Call AI APIs


import openai

Python Fundamentals & AI Automation Guide


Python for AI Automation Page 11

def ask_ai(prompt, model='gpt-4', max_tokens=500, temperature=0.7):

"""

Send a prompt to an AI model and return the text response.

Parameters:

prompt : The question or instruction to send

model : Which AI model to use

max_tokens : Maximum length of the response

temperature : Creativity (0=focused, 1=creative)

"""

client = [Link]()

response = [Link](

model=model,

messages=[{'role': 'user', 'content': prompt}],

max_tokens=max_tokens,

temperature=temperature

return [Link][0].[Link]

# Now reuse this function anywhere in your program

summary = ask_ai('Summarize the French Revolution in 3 sentences.')

poem = ask_ai('Write a haiku about Python.', temperature=0.9)

code = ask_ai('Write a Python function to sort a list.', model='gpt-4')

■ AI AUTOMATION: Functions in AI Automation

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.

Use Case How This Topic Helps

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)

Python Fundamentals & AI Automation Guide


Python for AI Automation Page 12

Batch processing def process_batch(items): loops through items calling the AI function for each one

Python Fundamentals & AI Automation Guide


Python for AI Automation Page 13

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.

The for Loop — Iterate Over a Sequence


# Loop over a list

fruits = ['apple', 'banana', 'cherry']

for fruit in fruits:

print(f'Processing: {fruit}')

# Loop with range() — repeat a fixed number of times

for i in range(5): # i goes 0, 1, 2, 3, 4

print(f'Attempt {i+1}')

# range(start, stop, step)

for n in range(0, 100, 10): # 0, 10, 20, ... 90

print(n)

# Loop over a list of prompts — batch AI processing

prompts = [

'Summarize quantum computing in 2 sentences.',

'Explain machine learning to a 10-year-old.',

'What is the difference between AI and AGI?'

results = []

for prompt in prompts:

response = ask_ai(prompt) # calls our function from Topic 4

[Link](response)

print(f'Done: {prompt[:40]}...')

The while Loop — Repeat Until a Condition Changes


# while loop — keeps going as long as condition is True

attempts = 0

max_attempts = 3

success = False

Python Fundamentals & AI Automation Guide


Python for AI Automation Page 14

while attempts < max_attempts and not success:

attempts += 1

print(f'Attempt {attempts}...')

response = ask_ai('Generate a valid JSON object.')

if [Link]('{'): # check if it looks like JSON

success = True

print('Valid response received!')

else:

print('Invalid response, retrying...')

# break — exit a loop early

# continue — skip to the next iteration

for item in data:

if item is None:

continue # skip None items

if len(item) > 1000:

break # stop if item is too large

process(item)

# List comprehension — a compact for loop that builds a list

scores = [0.9, 0.4, 0.8, 0.3, 0.95]

high_scores = [s for s in scores if s >= 0.7] # [0.9, 0.8, 0.95]

■ AI AUTOMATION: Loops in AI Automation

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.

Use Case How This Topic Helps

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

Python Fundamentals & AI Automation Guide


Python for AI Automation Page 15

Training ML models for epoch in range(100): [Link](batch); loss = evaluate() — the ML training
loop

Python Fundamentals & AI Automation Guide


Python for AI Automation Page 16

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.

Creating and Indexing Strings


# Creating strings

single = 'Hello'

double = "World"

multi = '''This is a

multi-line string

useful for long prompts'''

# String indexing — access individual characters

word = 'Python'

word[0] # 'P' — first character (index starts at 0)

word[-1] # 'n' — last character

# Slicing — extract a substring

word[0:3] # 'Pyt' — characters 0, 1, 2

word[2:] # 'thon' — from index 2 to end

word[:3] # 'Pyt' — from start to index 2

Essential String Methods for AI Work


text = ' Hello, World! '

# Cleaning

[Link]() # 'Hello, World!' — removes whitespace

[Link]() # 'hello, world!' — lowercase

[Link]() # 'HELLO, WORLD!' — uppercase

[Link]('World', 'AI') # 'Hello, AI!'

# Searching

[Link]('World') # 9 — index where substring starts (-1 if not found)

'Python' in text # True/False — check if substring exists

[Link]('He') # True

[Link]('!') # True

[Link]('l') # 3 — how many times 'l' appears

Python Fundamentals & AI Automation Guide


Python for AI Automation Page 17

# Splitting and joining

sentence = 'apple,banana,cherry'

words = [Link](',') # ['apple', 'banana', 'cherry']

','.join(words) # 'apple,banana,cherry' — reverse it

# f-strings — the most important string tool for AI prompts

topic = 'climate change'

audience = 'high school students'

length = 3

prompt = f'''You are an expert science communicator.

Explain {topic} to {audience} in exactly {length} paragraphs.

Use simple language and real-world examples.'''

# String formatting for AI responses

response = ' The answer is: 42. \n'

clean = [Link]().rstrip('.')

■ AI AUTOMATION: Strings in AI Automation

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.

Use Case How This Topic Helps

Prompt engineering f-strings let you build dynamic prompts: f'Translate this to {language}: {text}'

Response cleaning .strip(), .replace(), .lower() clean up inconsistent AI text outputs

Output validation [Link]('{') checks if AI returned JSON as requested

Text chunking for AI Split long documents into chunks that fit within token limits

Parsing AI output .split('\n') breaks line-by-line AI responses into processable lists

System prompt templates Triple-quoted strings hold multi-paragraph system prompts with clear formatting

Python Fundamentals & AI Automation Guide


Python for AI Automation Page 18

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

# Read entire file as one string

with open('[Link]', 'r', encoding='utf-8') as f:

content = [Link]()

# Read line by line (memory-efficient for large files)

with open('[Link]', 'r') as f:

for line in f:

line = [Link]() # remove newline characters

print(line)

# Read all lines into a list

with open('[Link]', 'r') as f:

lines = [Link]() # each element is one line

# Read a CSV file

import csv

with open('[Link]', 'r') as f:

reader = [Link](f) # each row becomes a dict

for row in reader:

print(row['name'], row['email'])

Writing Files
# Write (creates file or OVERWRITES existing)

with open('[Link]', 'w', encoding='utf-8') as f:

[Link]('AI-generated content here\n')

[Link]('Second line\n')

# Append (adds to existing file without overwriting)

with open('[Link]', 'a') as f:

[Link](f'Response received at 14:32: {response_text[:100]}\n')

Python Fundamentals & AI Automation Guide


Python for AI Automation Page 19

# Write JSON (perfect for AI responses — they are often JSON)

import json

data = {'prompt': 'Explain AI', 'response': 'AI stands for...', 'tokens': 142}

with open('[Link]', 'w') as f:

[Link](data, f, indent=2) # 'indent=2' makes it readable

# Read JSON back

with open('[Link]', 'r') as f:

loaded = [Link](f)

print(loaded['response']) # 'AI stands for...'

# Process a folder of text files and save AI summaries

import os

for filename in [Link]('documents/'):

if [Link]('.txt'):

with open(f'documents/{filename}') as f:

text = [Link]()

summary = ask_ai(f'Summarize: {text}')

with open(f'summaries/{filename}', 'w') as f:

[Link](summary)

■ AI AUTOMATION: Files in AI Automation

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.

Use Case How This Topic Helps

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

Python Fundamentals & AI Automation Guide


Python for AI Automation Page 20

Batch report generation For each customer in [Link], generate a personalized AI report and save
as PDF

Python Fundamentals & AI Automation Guide


Python for AI Automation Page 21

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.

Creating and Modifying Lists


# Create a list

models = ['gpt-4', 'claude-3-opus', 'gemini-pro']

scores = [0.92, 0.87, 0.95, 0.61, 0.78]

mixed = ['Alice', 28, True, 3.14] # lists can mix types

empty = [] # start empty and fill later

# Access by index

models[0] # 'gpt-4' — first item

models[-1] # 'gemini-pro' — last item

models[1:3] # ['claude-3-opus', 'gemini-pro'] — slicing

# Adding items

[Link]('llama-3') # add to end

[Link](0, 'gpt-3.5') # insert at position 0

[Link](['falcon', 'phi']) # add multiple items

# Removing items

[Link]('llama-3') # remove by value

last = [Link]() # remove and return last item

del models[0] # remove by index

# Useful list operations

len(models) # number of items

'gpt-4' in models # True — membership check

[Link]() # sort alphabetically in place

sorted(scores) # returns new sorted list, original unchanged

[Link]() # reverse in place

max(scores) # 0.95 — highest value

min(scores) # 0.61 — lowest value

sum(scores) / len(scores) # average

Python Fundamentals & AI Automation Guide


Python for AI Automation Page 22

Lists for Conversation History (Critical for AI Chatbots)


# AI APIs expect conversation history as a list of message dicts

conversation = []

def chat(user_message):

# Add user message to history

[Link]({'role': 'user', 'content': user_message})

# Send entire history to the AI (so it remembers context)

response = [Link](

model='gpt-4',

messages=conversation

ai_message = [Link][0].[Link]

# Add AI reply to history for next turn

[Link]({'role': 'assistant', 'content': ai_message})

return ai_message

chat('What is Python?') # Turn 1

chat('Give me an example.') # Turn 2 — AI remembers turn 1

■ AI AUTOMATION: Lists in AI Automation

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.

Use Case How This Topic Helps

Conversation memory conversation = [] stores the full chat history sent to the AI on every turn

Batch prompt processing prompts = [...]; for p in prompts: [Link](ask_ai(p))

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

Collecting results all_summaries = [] then all_summaries.append(summary) in a loop — gather AI


outputs

Python Fundamentals & AI Automation Guide


Python for AI Automation Page 23

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.

Creating and Using Dictionaries


# Create a dictionary

person = {

'name': 'Alice',

'age': 28,

'role': 'Data Scientist',

'skills': ['Python', 'ML', 'SQL'] # value can be any type

# Access values by key

person['name'] # 'Alice'

person['skills'] # ['Python', 'ML', 'SQL']

# Safe access with .get() — returns None if key doesn't exist

[Link]('email') # None (no KeyError)

[Link]('email', 'N/A') # 'N/A' — with a default value

# Add or update a key

person['email'] = 'alice@[Link]' # add new key

person['age'] = 29 # update existing key

# Remove a key

del person['age']

removed = [Link]('email') # removes and returns the value

# Check if a key exists

'name' in person # True

# Loop through a dictionary

for key, value in [Link]():

print(f'{key}: {value}')

# All keys or all values

[Link]() # dict_keys(['name', 'role', 'skills'])

Python Fundamentals & AI Automation Guide


Python for AI Automation Page 24

[Link]() # dict_values(['Alice', 'Data Scientist', [...]])

Dictionaries and AI API Calls


# Every AI API call uses a dictionary for the request body

request_body = {

'model': 'claude-3-opus-20240229',

'max_tokens': 1024,

'messages': [

{'role': 'user', 'content': 'Explain neural networks.'}

# AI API responses are also dictionaries (parsed from JSON)

response = {

'id': 'msg_01XFDUDYJgAACzvnptvVoYEL',

'model': 'claude-3-opus-20240229',

'usage': {'input_tokens': 15, 'output_tokens': 312},

'content': [{'type': 'text', 'text': 'Neural networks are...'}]

# Navigate nested dictionaries

answer = response['content'][0]['text']

tokens_in = response['usage']['input_tokens']

tokens_out = response['usage']['output_tokens']

# Store multiple AI responses indexed by prompt

cache = {}

def cached_ai(prompt):

if prompt in cache:

return cache[prompt] # return saved result (no API call)

result = ask_ai(prompt)

cache[prompt] = result # save for next time

return result

■ AI AUTOMATION: Dictionaries in AI Automation

Python Fundamentals & AI Automation Guide


Python for AI Automation Page 25

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.

Use Case How This Topic Helps

API request bodies {'model': 'gpt-4', 'messages': [...], 'temperature': 0.7} — the exact format APIs
expect

Parsing API responses response['choices'][0]['message']['content'] — navigating nested response dicts

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

Python Fundamentals & AI Automation Guide


Python for AI Automation Page 26

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.

Creating and Using Tuples


# Create a tuple with parentheses

point = (10, 20) # x, y coordinates

rgb = (255, 128, 0) # color values

model_info = ('gpt-4', 8192, 0.03) # name, context, price

# Access by index (same as lists)

point[0] # 10

point[1] # 20

# Tuples are IMMUTABLE — this raises an error

# point[0] = 99 # TypeError: 'tuple' object does not support item assignment

# Single-item tuple requires a trailing comma

single = ('only_item',) # without the comma it's just parentheses

# Unpacking — assign tuple values to variables

x, y = point # x=10, y=20

name, context, price = model_info

print(f'{name}: {context} tokens at ${price}/1k tokens')

# Functions returning multiple values actually return a tuple

def get_model_stats(model_name):

return model_name, 8192, 0.03 # returns a tuple

name, ctx, cost = get_model_stats('gpt-4')

# Tuple of tuples — a lightweight lookup table

AI_MODELS = (

('gpt-4', 8192, 0.03),

('gpt-3.5-turbo', 4096, 0.002),

('claude-3-opus', 200000, 0.015),

('claude-3-haiku', 200000, 0.00025),

Python Fundamentals & AI Automation Guide


Python for AI Automation Page 27

for model_name, context_len, price in AI_MODELS:

print(f'{model_name}: {context_len} tokens, ${price}/1k')

Tuples vs Lists — When to Use Which


Feature List Tuple

Syntax [1, 2, 3] (1, 2, 3)

Mutable Yes — can change No — fixed forever

Speed Slightly slower Slightly faster

Use when Data that changes Data that must not change

Dict key Cannot use as key Can use as a dict key

AI use case Message history list Model config constants

■ AI AUTOMATION: Tuples in AI Automation

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.

Use Case How This Topic Helps

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

Named tuples Response = namedtuple('Response', ['text','tokens','cost']) — readable AI output


struct

Immutable config ALLOWED_ROLES = ('user', 'assistant', 'system') — valid message role


constants

Python Fundamentals & AI Automation Guide


Python for AI Automation Page 28

Putting It All Together


Python + AI Automation: The Complete Picture

Python Fundamentals & AI Automation Guide


Python for AI Automation Page 29

How These 10 Topics Power AI Automation


Now that you have learned all ten Python fundamentals, here is how they combine in a real AI automation project. Every
script, agent, pipeline, or AI-powered application you build will use all ten of these concepts working together.

A Complete AI Automation Script — All 10 Topics in Action


# AI Document Summarizer — uses all 10 Python topics

import openai, json, os, csv

# VARIABLES — store configuration

MODEL = 'gpt-4'

MAX_TOKENS = 500

INPUT_FOLDER = 'documents/'

OUTPUT_FILE = '[Link]'

# DICTIONARY — store results

results = {}

# FUNCTION — reusable AI call

def summarize(text, style='concise'):

# STRINGS — build the prompt with f-string

prompt = f'Summarize the following in a {style} style:\n\n{text}'

client = [Link]()

response = [Link](

model=MODEL,

messages=[{'role': 'user', 'content': prompt}],

max_tokens=MAX_TOKENS

# TUPLE unpacking — extract multiple values

text_out = [Link][0].[Link]

tokens = [Link].total_tokens

return text_out, tokens

# FUNCTION — process all files

def process_folder(folder):

# LIST — collect filenames

files = [f for f in [Link](folder) if [Link]('.txt')]

total_tokens = 0

# LOOP — iterate over each file

Python Fundamentals & AI Automation Guide


Python for AI Automation Page 30

for filename in files:

# FILES — read document from disk

with open(f'{folder}{filename}', 'r') as f:

content = [Link]()

# CONDITIONAL — skip empty files

if len([Link]()) == 0:

print(f'Skipping empty file: {filename}')

continue

# EXPRESSIONS — calculate word count

word_count = len([Link]())

# CONDITIONAL — choose summarization style

if word_count > 2000:

style = 'bullet-point'

elif word_count > 500:

style = 'concise'

else:

style = 'one-sentence'

summary, tokens_used = summarize(content, style)

total_tokens += tokens_used

# DICTIONARY — store result

results[filename] = {

'summary': summary,

'word_count': word_count,

'tokens_used': tokens_used,

'style': style

print(f'Processed {filename} ({tokens_used} tokens)')

return total_tokens

# Run the pipeline

total = process_folder(INPUT_FOLDER)

# FILES — write JSON output

with open(OUTPUT_FILE, 'w') as f:

[Link](results, f, indent=2)

# EXPRESSIONS — calculate total cost

Python Fundamentals & AI Automation Guide


Python for AI Automation Page 31

cost = (total / 1000) * 0.03

print(f'Done! {len(results)} files. {total} tokens used. Cost: ${cost:.4f}')

The AI Automation Roadmap — What to Learn Next


With these 10 Python fundamentals mastered, here is a clear learning path toward building powerful AI automation systems:

Phase 1 (You
Python Fundamentals All 10 topics in this guide — the foundation of everything
are here)

Classes, objects, imports, packages — structure bigger


Phase 2 Python OOP & Modules
programs

Phase 3 APIs & HTTP requests library, REST APIs, JSON — talk to any web service

OpenAI, Anthropic, Hugging Face SDKs — build AI-powered


Phase 4 AI API Integration
scripts

System prompts, few-shot examples, chain-of-thought — get


Phase 5 Prompt Engineering
better AI outputs

Phase 6 LangChain / LlamaIndex Chains, agents, RAG, memory — build complex AI workflows

pandas, numpy, scikit-learn — analyze data and build ML


Phase 7 Data & ML
models

FastAPI, Docker, cloud hosting — make your AI automation


Phase 8 Deployment
production-ready

Recommended Learning Resources


• [Link]/doc — Official Python documentation and tutorials
• [Link]/docs — OpenAI API documentation with Python examples
• [Link] — Anthropic Claude API documentation
• [Link] — LangChain framework for building AI agents and chains
• [Link] — Practical deep learning for coders (free course)
• [Link]/learn — Free Python, pandas, and ML mini-courses
• [Link] — Excellent Python tutorials for all levels
• [Link] — Search for 'langchain examples', 'openai cookbook' for real project code

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.

Python Fundamentals & AI Automation Guide

You might also like