University of Texas at Austin | Great Learning | PGP in AI & ML
Every concept explained from scratch. No assumptions. Real-life examples for everything.
Notes prepared by: Vamshi Krishan Reddy Bandaru
int (42), float (3.14), str ("hello"), bool (True/False), None[1, 2, 3]. Use for collections that change.(1, 2, 3). Use for fixed data like coordinates.{"name": "AI"}. Use for labeled data, lookups.{1, 2, 3}. Use for membership tests, removing duplicates.if/elif/else for branching. for/while for loops. Indentation matters!This Pre-Work module establishes the foundation for the entire PGP program. Understanding the AI landscape gives you context for every technique you will learn. Mastering Python basics ensures you can implement those techniques from Day 1.
How all Pre-Work topics connect together:
| Aspect | AI | ML | Deep Learning | GenAI | LLMs |
|---|---|---|---|---|---|
| Definition | Machines that mimic intelligence | Learn from data | Multi-layer neural nets | Creates new content | Text-focused GenAI |
| Data Needed | Can be rule-based (none) | Moderate | Large | Very large | Massive text corpora |
| Feature Eng. | Manual rules | Manual features | Automatic | Automatic | Automatic |
| Example | Chess engine (1997) | Spam filter | Image recognition | DALL-E, Midjourney | GPT-4, Claude |
| Compute | Low-High | Moderate | High | Very High | Extremely High |
Key Insight: AI has gone through multiple hype cycles and "winters." The current wave is different because of three converging factors: massive data availability, cheap compute (GPUs/cloud), and algorithmic breakthroughs (transformers). Understanding this history helps you evaluate new AI claims critically.
| Feature | Narrow AI (ANI) | General AI (AGI) | Super AI (ASI) |
|---|---|---|---|
| Status | ✅ Exists now | 🔭 Research phase | 🔮 Theoretical |
| Scope | Single task/domain | All human cognitive tasks | Exceeds all human abilities |
| Learning | Task-specific training | Transfer learning across domains | Self-improving beyond human design |
| Creativity | Within narrow bounds | Human-level creativity | Beyond human imagination |
| Examples | GPT-4, AlphaGo, DALL-E | None yet | None yet |
| Timeline | Now | Debated: 2030-2060+ | Unknown / may never happen |
AI is transforming every major industry. Understanding where AI creates value helps you identify opportunities and frame problems correctly throughout the PGP program.
| Industry | AI Application | Business Impact | ML Type |
|---|---|---|---|
| Healthcare | Medical image diagnosis, drug discovery, patient readmission prediction | Earlier detection, 30-40% faster diagnosis | Supervised, DL |
| Finance | Fraud detection, algorithmic trading, credit scoring, risk assessment | Real-time fraud prevention, better risk models | Supervised, RL |
| Retail | Recommendation engines, demand forecasting, dynamic pricing | 35% of Amazon revenue from recommendations | Supervised, Unsupervised |
| Manufacturing | Predictive maintenance, quality control, supply chain optimization | Reduce downtime by 30-50%, fewer defects | Supervised, Unsupervised |
| Transportation | Self-driving vehicles, route optimization, traffic prediction | Safer roads, reduced logistics costs | DL, RL |
| Marketing | Customer segmentation, churn prediction, ad targeting | Higher ROI, personalized experiences | Supervised, Unsupervised |
| Agriculture | Crop disease detection, yield prediction, precision farming | Increased yields, reduced waste | DL, Supervised |
| Education | Personalized learning, automated grading, dropout prediction | Better outcomes, scalable instruction | Supervised, NLP |
Problem: With 17,000+ titles, users struggle to find content they enjoy. Poor recommendations lead to churn.
AI Solution: Collaborative filtering + content-based filtering + deep learning. Analyzes viewing history, ratings, time of day, device, and even thumbnail engagement.
Impact: Recommendations drive 80% of watched content. Saves Netflix an estimated $1 billion per year in reduced churn.
ML Types Used: Supervised learning (predict ratings), Unsupervised (user clusters), Deep learning (visual features).
Problem: Lawyers spent 360,000 hours annually reviewing commercial loan agreements.
AI Solution: NLP-based system that reads and interprets legal documents, extracts key data points, and flags anomalies.
Impact: Reduced review time from 360,000 hours to seconds. Fewer errors than human reviewers. Freed lawyers for higher-value work.
ML Types Used: NLP, Supervised learning, Deep learning for text understanding.
Problem: Farmers spray herbicides uniformly, wasting chemicals on bare soil and harming the environment.
AI Solution: Computer vision cameras on sprayers identify weeds in real-time and spray only where needed (See & Spray technology).
Impact: Reduces herbicide use by up to 77%. Saves farmers thousands per season while being environmentally sustainable.
ML Types Used: Deep learning (image classification), real-time inference at the edge.
Framework for AI Opportunities: Look for tasks that are (1) repetitive, (2) data-rich, (3) require pattern recognition, and (4) have clear success metrics. These are the best candidates for AI solutions in any industry.
colab.research.google.com. Sign in with your Google account.Shift+Enter to run it.# Check Python version
import sys
print(sys.version)
# Mount Google Drive to access your files
from google.colab import drive
drive.mount('/content/drive')
# Install a library not in Colab by default
!pip install xgboost
# Upload files from your computer
from google.colab import files
uploaded = files.upload()
# Download a file to your computer
files.download('my_model.pkl')
| Shortcut | Action | When to Use |
|---|---|---|
Shift + Enter | Run cell & move to next | Most common. Run and continue. |
Ctrl + Enter | Run cell & stay | When iterating on a single cell. |
Alt + Enter | Run cell & insert new below | When building code step by step. |
Ctrl + M + B | Insert code cell below | Add a new cell quickly. |
Ctrl + M + D | Delete current cell | Clean up unused cells. |
Ctrl + / | Toggle comment | Comment/uncomment selected lines. |
Ctrl + Shift + H | Show keyboard shortcuts | Discover more shortcuts. |
Ctrl + S | Save notebook | Save your work (also auto-saves). |
Pro Tip: Always mount Google Drive at the start of your notebook. Save datasets and model checkpoints to Drive so you never lose work when the Colab session disconnects (free tier disconnects after ~90 min of inactivity).
=. No need to declare types — Python figures it out automatically (dynamic typing).age = 25 creates a box labeled "age" containing the number 25.| Type | Python Name | Examples | Used For |
|---|---|---|---|
| Integer | int | 42, -7, 0 | Counting, indexing, whole numbers |
| Float | float | 3.14, -0.5, 1e10 | Decimals, measurements, probabilities |
| String | str | "hello", 'AI' | Text, names, labels, file paths |
| Boolean | bool | True, False | Conditions, flags, filters |
| None | NoneType | None | Missing/empty values, default returns |
# Creating variables — Python infers the type
name = "Vamshi" # str
age = 25 # int
gpa = 3.85 # float
is_student = True # bool
scholarship = None # NoneType
# Check type with type()
print(type(name)) # <class 'str'>
print(type(age)) # <class 'int'>
print(type(gpa)) # <class 'float'>
# Check type with isinstance()
print(isinstance(age, int)) # True
int(), float(), str(), bool(). Essential when combining data from different sources.# Explicit type conversion
x = "42" # string
y = int(x) # now integer 42
z = float(x) # now float 42.0
# Common pitfall — can't convert non-numeric strings
# int("hello") # ValueError!
# Implicit conversion (Python does it automatically)
result = 5 + 3.0 # int + float = float (8.0)
# Boolean conversions (truthy/falsy)
bool(0) # False (zero is falsy)
bool(42) # True (non-zero is truthy)
bool("") # False (empty string is falsy)
bool("hello") # True (non-empty is truthy)
bool([]) # False (empty list is falsy)
bool(None) # False (None is falsy)
Why this matters for AI/ML: Data from CSV files comes in as strings. You will constantly convert types: "3.14" → 3.14, "True" → True. Understanding truthy/falsy is critical for data filtering and cleaning with Pandas.
type(3.0)?bool([]) return?| Operator | Name | Example | Result | ML Use Case |
|---|---|---|---|---|
+ | Addition | 7 + 3 | 10 | Summing features, loss accumulation |
- | Subtraction | 7 - 3 | 4 | Residuals (actual - predicted) |
* | Multiplication | 7 * 3 | 21 | Weights * features in linear models |
/ | Division | 7 / 3 | 2.333... | Normalization, averaging |
// | Floor Division | 7 // 3 | 2 | Batch indexing, integer splits |
% | Modulo | 7 % 3 | 1 | Cyclic features (day of week) |
** | Exponentiation | 2 ** 3 | 8 | Squared errors, polynomial features |
# Arithmetic in action — MSE calculation
actual = 100
predicted = 95
error = actual - predicted # 5 (residual)
sq_error = error ** 2 # 25 (squared error)
# Floor division for batching
total_samples = 1000
batch_size = 32
num_batches = total_samples // batch_size # 31
leftover = total_samples % batch_size # 8
| Operator | Meaning | Example | Result |
|---|---|---|---|
== | Equal to | 5 == 5 | True |
!= | Not equal to | 5 != 3 | True |
> | Greater than | 5 > 3 | True |
< | Less than | 5 < 3 | False |
>= | Greater or equal | 5 >= 5 | True |
<= | Less or equal | 5 <= 3 | False |
| Operator | Meaning | Example | Result |
|---|---|---|---|
and | Both must be True | True and False | False |
or | At least one True | True or False | True |
not | Inverts the value | not True | False |
# Practical: Filter conditions for ML data
age = 30
income = 75000
has_degree = True
# Complex condition
is_target = (age >= 25) and (income > 50000) and has_degree
print(is_target) # True
# Chaining comparisons (Python allows this!)
score = 85
print(70 <= score <= 90) # True (same as: score >= 70 and score <= 90)
Why this matters for AI/ML: Every data filter in Pandas uses comparison operators: df[df['age'] > 25]. Every decision tree split is a comparison. Understanding operator precedence prevents subtle bugs in feature engineering.
x = 10
x += 5 # x = x + 5 → 15
x -= 3 # x = x - 3 → 12
x *= 2 # x = x * 2 → 24
x /= 4 # x = x / 4 → 6.0
x **= 2 # x = x ** 2 → 36.0
# Multiple ways to create strings
s1 = "Hello, World!" # double quotes
s2 = 'Hello, World!' # single quotes (identical)
s3 = """Multi-line
string spanning
several lines""" # triple quotes
s4 = "He said \"hello\"" # escaping quotes
s5 = r"C:\new\folder" # raw string (no escape)
text = "Machine Learning"
# Indexing (0-based)
print(text[0]) # "M"
print(text[-1]) # "g" (last character)
# Slicing [start:stop:step]
print(text[0:7]) # "Machine"
print(text[8:]) # "Learning"
print(text[::-1]) # "gninraeL enihcaM" (reverse)
# Common methods
print(text.upper()) # "MACHINE LEARNING"
print(text.lower()) # "machine learning"
print(text.split()) # ["Machine", "Learning"]
print(text.replace("Machine", "Deep")) # "Deep Learning"
print(len(text)) # 16
print("Learn" in text) # True (membership test)
f and put expressions in {}. Much cleaner than % or .format().model_name = "Random Forest"
accuracy = 0.9543
n_trees = 100
# f-string with formatting
print(f"Model: {model_name}")
# "Model: Random Forest"
print(f"Accuracy: {accuracy:.2%}")
# "Accuracy: 95.43%"
print(f"Trees: {n_trees:,} | Acc: {accuracy:.4f}")
# "Trees: 100 | Acc: 0.9543"
# Expressions inside f-strings
print(f"Error rate: {(1 - accuracy) * 100:.2f}%")
# "Error rate: 4.57%"
Why this matters for AI/ML: String operations are essential for text preprocessing in NLP: tokenization (split()), normalization (lower()), cleaning (strip(), replace()). f-strings are used everywhere for logging model metrics and formatting outputs.
"Hello World"[6:] return?Data structures determine how you store, organize, and access data. Choosing the right one is fundamental to writing efficient Python code for data science.
[]. The most versatile and commonly used data structure in Python.["apples", "bread", "milk"] — you can add, remove, or reorder items at any time.# Creating and manipulating lists
scores = [85, 92, 78, 95, 88]
# Indexing and slicing
print(scores[0]) # 85 (first)
print(scores[-1]) # 88 (last)
print(scores[1:4]) # [92, 78, 95]
# Modifying (lists are mutable!)
scores.append(91) # Add to end: [85, 92, 78, 95, 88, 91]
scores.insert(0, 100) # Insert at index 0
scores.remove(78) # Remove first occurrence of 78
popped = scores.pop() # Remove and return last item
# Useful operations
print(len(scores)) # Length
print(sorted(scores)) # Returns sorted copy
print(sum(scores)) # Sum all elements
print(max(scores)) # Maximum value
print(min(scores)) # Minimum value
# List comprehension (concise way to create lists)
squares = [x**2 for x in range(1, 6)] # [1, 4, 9, 16, 25]
(). Once created, you cannot add, remove, or change elements. Faster and safer than lists for fixed data.(37.7749, -122.4194) — latitude and longitude shouldn't change.# Tuples are immutable
coordinates = (37.7749, -122.4194)
rgb_color = (255, 128, 0)
model_config = ("RandomForest", 100, 0.8)
# Tuple unpacking
lat, lon = coordinates
print(f"Lat: {lat}, Lon: {lon}")
# coordinates[0] = 40.0 # TypeError! Tuples are immutable
{}. Keys must be unique and immutable (strings, numbers, tuples). Values can be anything.{"name": "Vamshi", "age": 25, "program": "AI/ML"} — look up any field by name.# Creating and using dictionaries
model_results = {
"model": "XGBoost",
"accuracy": 0.9534,
"precision": 0.9412,
"recall": 0.9621,
"f1_score": 0.9515
}
# Access values
print(model_results["accuracy"]) # 0.9534
print(model_results.get("auc", "N/A")) # "N/A" (safe access)
# Add/modify
model_results["auc"] = 0.9801 # Add new key
model_results["accuracy"] = 0.9567 # Update existing
# Iterate
for metric, value in model_results.items():
print(f"{metric}: {value}")
# Useful methods
print(model_results.keys()) # all keys
print(model_results.values()) # all values
{} or set(). Automatically removes duplicates. Supports mathematical set operations (union, intersection, difference).# Sets auto-remove duplicates
features_v1 = {"age", "income", "education", "age"}
print(features_v1) # {"age", "income", "education"} (no dupe)
features_v2 = {"age", "income", "location", "gender"}
# Set operations
print(features_v1 | features_v2) # Union: all features
print(features_v1 & features_v2) # Intersection: common features
print(features_v1 - features_v2) # Difference: in v1 but not v2
| Structure | Ordered? | Mutable? | Duplicates? | Best For |
|---|---|---|---|---|
List [] | ✅ Yes | ✅ Yes | ✅ Yes | General collections, sequences, stacks |
Tuple () | ✅ Yes | ❌ No | ✅ Yes | Fixed data, dict keys, function returns |
Dict {k:v} | ✅ (3.7+) | ✅ Yes | Keys: No | Labeled data, lookups, configs, JSON |
Set {} | ❌ No | ✅ Yes | ❌ No | Uniqueness, membership tests, dedup |
{1, 2, 2, 3, 3, 3}?if/elif/else lets your program make decisions. Without control flow, code runs top-to-bottom with no branching.# Basic if/elif/else
accuracy = 0.87
if accuracy >= 0.95:
print("Excellent model! Ready for production.")
elif accuracy >= 0.85:
print("Good model. Consider hyperparameter tuning.")
elif accuracy >= 0.70:
print("Acceptable. Try feature engineering.")
else:
print("Poor model. Revisit data and approach.")
# Output: "Good model. Consider hyperparameter tuning."
# Nested conditions for complex logic
has_gpu = True
dataset_size = 50000
task = "image_classification"
if task == "image_classification":
if has_gpu and dataset_size > 10000:
model = "Deep CNN"
elif dataset_size > 1000:
model = "Transfer Learning"
else:
model = "Simple CNN + Augmentation"
else:
model = "XGBoost"
print(f"Recommended: {model}")
# Output: "Recommended: Deep CNN"
# Ternary: value_if_true if condition else value_if_false
accuracy = 0.92
status = "Pass" if accuracy >= 0.9 else "Fail"
print(status) # "Pass"
# Practical: label encoding
label = 1 if prediction > 0.5 else 0
# Practical: handling missing values
value = data.get("score") if data else 0
# Check for None explicitly
if value is None:
print("Missing!")
# Use 'in' for membership
if ext in [".csv", ".xlsx"]:
print("Data file!")
# Chain comparisons
if 0 <= prob <= 1:
print("Valid")
# Don't use == for None
if value == None: # works but wrong
print("Missing!")
# Don't chain OR for each
if ext==".csv" or ext==".xlsx":
print("Data file!")
# Don't split comparisons
if prob>=0 and prob<=1:
print("Valid")
Why this matters for AI/ML: Control flow is everywhere in ML pipelines: choosing algorithms based on data size, handling missing values, implementing early stopping, routing data through different preprocessing paths. Every decision tree literally IS a nested if/elif/else structure.
"Yes" if 10 > 5 else "No" evaluate to?if x = 5: — SyntaxError! Assignment (=) used where comparison (==) was intended.= assigns a value. == compares values. Always use == in conditions: if x == 5:. Python catches this as a SyntaxError, but it confuses beginners."5" + 3 → TypeError! Python doesn't auto-convert between strings and numbers like JavaScript.int("5") + 3 = 8, or "5" + str(3) = "53". In data science, this is extremely common when loading CSV data where numbers arrive as strings.for item in my_list: my_list.remove(item) — skips elements and produces unexpected results.new_list = [item for item in my_list if condition]. Or iterate over a copy: for item in my_list[:]:. List comprehensions are both safer and more Pythonic.def add_item(item, lst=[]): lst.append(item); return lst — the default list is shared across all calls!def add_item(item, lst=None): if lst is None: lst = []; lst.append(item); return lst. This is one of Python's most notorious gotchas.is to compare values: if x is 5: may work for small integers but fails for larger ones.== for value comparison, is only for identity (same object). Exception: always use is for None: if x is None:. Python caches small integers (-5 to 256), which is why is sometimes works by accident.my_list[1] to return the first element.my_list[0] is the first element. my_list[1] is the second. This applies to lists, tuples, strings, and NumPy arrays. Off-by-one errors are the #1 bug in data processing.if, for, def, etc.Golden Rule: The best way to learn Python is by writing Python. Don't just read examples — type them into Colab, modify them, break them, and fix them. Every error message is a learning opportunity. The Pre-Work is your foundation; invest time here and every subsequent module becomes easier.