Pre-Work: Introduction to AI Landscape & Python Programming

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

⚡ Cheat Sheet

AI Landscape at a Glance

Artificial Intelligence
Machines that mimic human intelligence. Broadest umbrella covering all approaches from rule-based to learning systems.
Machine Learning
Subset of AI. Systems that learn patterns from data without explicit programming. Needs structured data + features.
Deep Learning
Subset of ML. Neural networks with many layers. Learns features automatically from raw data. Needs lots of data + compute.
Generative AI
Subset of DL. Creates new content (text, images, code). Built on transformers, diffusion models, and foundation models.
LLMs
Subset of GenAI. Large Language Models trained on massive text. GPT-4, Claude, Llama. Understand and generate human language.
Why Python?
De facto language for AI/ML. Rich ecosystem: NumPy, Pandas, Scikit-learn, TensorFlow, PyTorch. Easy syntax, huge community.

Python Essentials Quick Reference

Data Types
int (42), float (3.14), str ("hello"), bool (True/False), None
Lists
Ordered, mutable, duplicates OK. [1, 2, 3]. Use for collections that change.
Tuples
Ordered, immutable, duplicates OK. (1, 2, 3). Use for fixed data like coordinates.
Dictionaries
Key-value pairs, mutable. {"name": "AI"}. Use for labeled data, lookups.
Sets
Unordered, unique items. {1, 2, 3}. Use for membership tests, removing duplicates.
Control Flow
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.

🗺 Concept Map

How all Pre-Work topics connect together:

Pre-Work Module: Complete Knowledge Map
🎓 PRE-WORK MODULE
▼
🤖 AI Landscape
🐍 Python Programming
▼
What is AI?
AI vs ML vs DL
AI in Business
▼
Variables & Types
Operators
Strings
▼
Data Structures
Control Flow
Google Colab
▼
Ready for Module 01: Python Foundations

Learning Path

1
AI Landscape — Understand what AI is, its types, history, and real-world business applications. This is your "why" for the entire program.
2
Google Colab Setup — Set up your coding environment. Colab gives you free GPU access and zero setup hassle.
3
Python Basics — Variables, data types, operators, strings. The atoms of every program you will write.
4
Data Structures — Lists, tuples, dicts, sets. How you store, organize, and access data efficiently.
5
Control Flow — if/elif/else, ternary. Making decisions in code. The logic layer of every ML pipeline.

🤖 Introduction to AI Landscape

Artificial Intelligence (AI)
The science and engineering of creating machines capable of performing tasks that typically require human intelligence: reasoning, learning, problem-solving, perception, and language understanding.
A spam filter that learns to identify unwanted emails, or a self-driving car navigating traffic.
Think of AI as a giant tree. The trunk is AI itself (the broadest concept). The main branches are Machine Learning, the smaller branches are Deep Learning, and the newest leaves are Generative AI and LLMs. Each level builds on the one before it, getting more specialized and powerful.

AI vs ML vs Deep Learning vs GenAI vs LLMs

The AI Hierarchy: Nested Subsets
🤖 ARTIFICIAL INTELLIGENCE
Broadest: any system mimicking human intelligence
▼
🧠 MACHINE LEARNING
Systems that learn from data without explicit rules
▼
🧠 DEEP LEARNING
Multi-layer neural networks
▼
✍ GENERATIVE AI
Creates new content
▼
💬 LLMs
Language-focused GenAI
AspectAIMLDeep LearningGenAILLMs
DefinitionMachines that mimic intelligenceLearn from dataMulti-layer neural netsCreates new contentText-focused GenAI
Data NeededCan be rule-based (none)ModerateLargeVery largeMassive text corpora
Feature Eng.Manual rulesManual featuresAutomaticAutomaticAutomatic
ExampleChess engine (1997)Spam filterImage recognitionDALL-E, MidjourneyGPT-4, Claude
ComputeLow-HighModerateHighVery HighExtremely High

History & Evolution of AI

AI Timeline: From Turing to Transformers
📚 1950
Turing Test proposed
💡 1956
Dartmouth: "AI" coined
🧠 1957
Perceptron invented
▼
❄ 1974-80
First AI Winter
📈 1980s
Expert Systems boom
❄ 1987-93
Second AI Winter
▼
♟ 1997
Deep Blue beats Kasparov
📸 2012
AlexNet: DL revolution
🚀 2017
Transformer paper
▼
🤖 2020
GPT-3: GenAI begins
💬 2022-23
ChatGPT, Claude, Bard
🌏 2024+
Multimodal, Agents
💡

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.

📝 Knowledge Check: AI Landscape
Q1: Which statement best describes the relationship between AI, ML, and Deep Learning?
Q2: What event is considered the birth of AI as a formal field?

🛠 Types of AI

Narrow AI (Weak AI / ANI)
AI designed and trained for a specific task. It excels at one thing but cannot transfer knowledge to other domains. This is ALL AI that exists today.
Siri answering questions, Netflix recommending movies, Tesla autopilot driving on highways. Each can only do its one job.
General AI (Strong AI / AGI)
Hypothetical AI with human-level intelligence across all cognitive tasks. Could learn any intellectual task a human can, transfer knowledge between domains, and reason abstractly.
An AI that could write code, compose music, diagnose diseases, AND carry a natural conversation — all without retraining. Does not exist yet.
Super AI (ASI)
Theoretical AI that surpasses human intelligence in all aspects: creativity, problem-solving, social intelligence. Purely theoretical and widely debated.
An intelligence that could solve climate change, cure cancer, and advance science beyond human capability simultaneously. Science fiction for now.
Think of it like cooking skills. Narrow AI is a chef who only makes pizza (amazing pizza, but can't boil an egg). General AI is a chef who can cook any cuisine at a professional level. Super AI is a chef who invents entirely new cuisines that humans couldn't even imagine.
Types of AI: Current vs. Future
✅ NARROW AI
Exists today
Siri, Alexa, ChatGPT, Self-driving
🔭 GENERAL AI
Research stage
Human-level across all tasks
🔮 SUPER AI
Theoretical
Surpasses all human intelligence
FeatureNarrow AI (ANI)General AI (AGI)Super AI (ASI)
Status✅ Exists now🔭 Research phase🔮 Theoretical
ScopeSingle task/domainAll human cognitive tasksExceeds all human abilities
LearningTask-specific trainingTransfer learning across domainsSelf-improving beyond human design
CreativityWithin narrow boundsHuman-level creativityBeyond human imagination
ExamplesGPT-4, AlphaGo, DALL-ENone yetNone yet
TimelineNowDebated: 2030-2060+Unknown / may never happen

ML Learning Paradigms

Supervised Learning
Model learns from labeled data (input-output pairs). You give it questions AND answers, and it learns the mapping.
Email spam detection: trained on thousands of emails labeled "spam" or "not spam." Predicting house prices from features like area, bedrooms, location.
Unsupervised Learning
Model finds patterns in data without labels. No "right answers" — the model discovers structure on its own.
Customer segmentation: grouping shoppers by behavior without predefined categories. Anomaly detection in credit card transactions.
Reinforcement Learning
Model learns by trial and error, receiving rewards for good actions and penalties for bad ones. Optimizes for maximum cumulative reward.
AlphaGo learning to play Go by playing millions of games against itself. A robot learning to walk by trying and falling.
Three Pillars of Machine Learning
🧠 MACHINE LEARNING
▼
Supervised
Labeled data
Classification, Regression
Unsupervised
No labels
Clustering, Dim. Reduction
Reinforcement
Rewards/Penalties
Game AI, Robotics
📝 Knowledge Check: Types of AI
Q3: Which type of AI is ChatGPT an example of?
Q4: A model trained on customer purchase data (without labels) to find distinct customer groups is using:

💼 AI in Business

AI is transforming every major industry. Understanding where AI creates value helps you identify opportunities and frame problems correctly throughout the PGP program.

Industry Applications

IndustryAI ApplicationBusiness ImpactML Type
HealthcareMedical image diagnosis, drug discovery, patient readmission predictionEarlier detection, 30-40% faster diagnosisSupervised, DL
FinanceFraud detection, algorithmic trading, credit scoring, risk assessmentReal-time fraud prevention, better risk modelsSupervised, RL
RetailRecommendation engines, demand forecasting, dynamic pricing35% of Amazon revenue from recommendationsSupervised, Unsupervised
ManufacturingPredictive maintenance, quality control, supply chain optimizationReduce downtime by 30-50%, fewer defectsSupervised, Unsupervised
TransportationSelf-driving vehicles, route optimization, traffic predictionSafer roads, reduced logistics costsDL, RL
MarketingCustomer segmentation, churn prediction, ad targetingHigher ROI, personalized experiencesSupervised, Unsupervised
AgricultureCrop disease detection, yield prediction, precision farmingIncreased yields, reduced wasteDL, Supervised
EducationPersonalized learning, automated grading, dropout predictionBetter outcomes, scalable instructionSupervised, NLP

Case Studies

Case 1: Netflix Recommendation Engine

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

Case 2: JPMorgan COIN (Contract Intelligence)

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.

Case 3: John Deere Precision Agriculture

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.

Think of AI in business like electricity in the early 1900s. At first, only a few industries used it. Then it became a "general purpose technology" that transformed everything. AI is following the same trajectory — it is not a product, it is an ingredient that makes every product better.
💡

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.

📝 Knowledge Check: AI in Business
Q5: What percentage of Netflix watched content is driven by AI recommendations?

💻 Google Colab Setup

Google Colaboratory (Colab)
A free, cloud-based Jupyter notebook environment from Google. Runs Python in your browser with zero setup. Provides free access to GPUs and TPUs for compute-intensive ML tasks.
Instead of installing Python, Anaconda, and libraries on your laptop, you open colab.research.google.com and start coding immediately.
Colab is like Google Docs for code. Just as Google Docs lets you write documents without installing Word, Colab lets you write and run Python without installing anything. It is saved to your Google Drive and shareable with a link.

Why Use Colab for This Program?

  • Zero Setup: No installation needed. Works on any device with a browser (even a Chromebook or tablet).
  • Free GPU/TPU: Train deep learning models without buying expensive hardware. Free tier includes T4 GPU.
  • Pre-installed Libraries: NumPy, Pandas, Scikit-learn, TensorFlow, PyTorch all come pre-installed.
  • Google Drive Integration: Save notebooks directly to Drive. Access datasets from Drive seamlessly.
  • Collaboration: Share notebooks like Google Docs. Real-time collaborative editing.
  • Version History: Automatic versioning. Never lose your work.

Getting Started with Colab

1
Open Colab: Navigate to colab.research.google.com. Sign in with your Google account.
2
Create a Notebook: Click "New Notebook." You get a blank notebook with one code cell ready to go.
3
Write Code: Click the code cell, type Python code, and press Shift+Enter to run it.
4
Add Cells: Use "+ Code" for code cells or "+ Text" for markdown explanations.
5
Enable GPU: Runtime → Change runtime type → T4 GPU. Use this for deep learning tasks.

Essential Colab Code

# 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')

Keyboard Shortcuts

ShortcutActionWhen to Use
Shift + EnterRun cell & move to nextMost common. Run and continue.
Ctrl + EnterRun cell & stayWhen iterating on a single cell.
Alt + EnterRun cell & insert new belowWhen building code step by step.
Ctrl + M + BInsert code cell belowAdd a new cell quickly.
Ctrl + M + DDelete current cellClean up unused cells.
Ctrl + /Toggle commentComment/uncomment selected lines.
Ctrl + Shift + HShow keyboard shortcutsDiscover more shortcuts.
Ctrl + SSave notebookSave 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).

📄 Variables & Data Types

Variable
A named container that stores a value in memory. In Python, you create variables by simply assigning a value with =. No need to declare types — Python figures it out automatically (dynamic typing).
Like a labeled box: age = 25 creates a box labeled "age" containing the number 25.
Variables are like labeled jars in a kitchen. Each jar has a name (the variable name) and contains something (the value). You can change what is inside the jar at any time, and you can even put a completely different type of ingredient in it.

Python Data Types

TypePython NameExamplesUsed For
Integerint42, -7, 0Counting, indexing, whole numbers
Floatfloat3.14, -0.5, 1e10Decimals, measurements, probabilities
Stringstr"hello", 'AI'Text, names, labels, file paths
BooleanboolTrue, FalseConditions, flags, filters
NoneNoneTypeNoneMissing/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

Type Conversion (Casting)

Type Conversion
Changing a value from one type to another. Python provides built-in functions: 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.

📝 Knowledge Check: Variables & Types
Q6: What is the output of type(3.0)?
Q7: What does bool([]) return?

✍ Operators

Arithmetic Operators

OperatorNameExampleResultML Use Case
+Addition7 + 310Summing features, loss accumulation
-Subtraction7 - 34Residuals (actual - predicted)
*Multiplication7 * 321Weights * features in linear models
/Division7 / 32.333...Normalization, averaging
//Floor Division7 // 32Batch indexing, integer splits
%Modulo7 % 31Cyclic features (day of week)
**Exponentiation2 ** 38Squared 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

Comparison Operators

OperatorMeaningExampleResult
==Equal to5 == 5True
!=Not equal to5 != 3True
>Greater than5 > 3True
<Less than5 < 3False
>=Greater or equal5 >= 5True
<=Less or equal5 <= 3False

Logical Operators

OperatorMeaningExampleResult
andBoth must be TrueTrue and FalseFalse
orAt least one TrueTrue or FalseTrue
notInverts the valuenot TrueFalse
# 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.

Assignment Operators (Shortcuts)

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

🔤 Strings

String (str)
An ordered, immutable sequence of characters enclosed in quotes. Strings are the primary way to handle text data in Python. Immutable means you cannot change individual characters — you must create a new string.

Creating Strings

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

String Operations

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-Strings (Formatted String Literals)

f-String (Python 3.6+)
The modern way to embed expressions inside strings. Prefix with 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.

📝 Knowledge Check: Strings
Q8: What does "Hello World"[6:] return?

📦 Data Structures

Data structures determine how you store, organize, and access data. Choosing the right one is fundamental to writing efficient Python code for data science.

Lists

List
An ordered, mutable collection that can hold items of any type. Created with square brackets []. The most versatile and commonly used data structure in Python.
A shopping list: ["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]

Tuples

Tuple
An ordered, immutable collection. Created with parentheses (). Once created, you cannot add, remove, or change elements. Faster and safer than lists for fixed data.
GPS coordinates: (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

Dictionaries

Dictionary (dict)
An unordered collection of key-value pairs. Created with curly braces {}. Keys must be unique and immutable (strings, numbers, tuples). Values can be anything.
A student record: {"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

Sets

Set
An unordered collection of unique elements. Created with {} 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

When to Use Which?

StructureOrdered?Mutable?Duplicates?Best For
List []✅ Yes✅ Yes✅ YesGeneral collections, sequences, stacks
Tuple ()✅ Yes❌ No✅ YesFixed data, dict keys, function returns
Dict {k:v}✅ (3.7+)✅ YesKeys: NoLabeled data, lookups, configs, JSON
Set {}❌ No✅ Yes❌ NoUniqueness, membership tests, dedup
Think of data structures like containers: A list is a numbered locker row (ordered, can swap items). A tuple is a sealed evidence bag (ordered, can't tamper). A dictionary is a filing cabinet with labeled folders (look up by name). A set is a bag of unique marbles (no duplicates, no order).
📝 Knowledge Check: Data Structures
Q9: You need to store configuration settings where each setting has a name and value. Which data structure is best?
Q10: What happens when you run {1, 2, 2, 3, 3, 3}?

🔀 Conditional Statements & Control Flow

Control Flow
The order in which individual statements, instructions, or function calls are executed. if/elif/else lets your program make decisions. Without control flow, code runs top-to-bottom with no branching.
A spam filter: IF email contains "lottery" AND sender is unknown, THEN mark as spam, ELSE deliver to inbox.

if / elif / else

# 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."
Control Flow: Decision Tree
Check Accuracy
▼
≥ 0.95?
Excellent
≥ 0.85?
Good
≥ 0.70?
Acceptable
else
Poor

Nested Conditions

# 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 Expressions (One-line if)

# 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

Common Patterns

✅ Do This

# 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")

❌ Avoid This

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

📝 Knowledge Check: Control Flow
Q11: What is the Pythonic way to check if a variable is None?
Q12: What does "Yes" if 10 > 5 else "No" evaluate to?

⚠ Common Mistakes & Misconceptions

AI Landscape Mistakes

1. "AI and Machine Learning are the same thing"
Using AI and ML interchangeably in conversations and project proposals.
✓ AI is the broad field; ML is one approach within AI. Rule-based expert systems are AI but not ML. All ML is AI, but not all AI is ML. Be precise in your terminology.
2. "ChatGPT is AGI (General AI)"
Believing current language models have achieved general intelligence because they seem to "understand" everything.
✓ ChatGPT, Claude, etc. are Narrow AI — incredibly good at language tasks but cannot do physical tasks, truly reason about novel problems, or transfer to unrelated domains. Impressive does not equal general.
3. "AI will replace all jobs"
Assuming AI automates entire jobs rather than specific tasks within jobs.
✓ AI typically automates tasks, not jobs. A radiologist's image reading may be augmented by AI, but patient communication, treatment planning, and clinical judgment still require humans. Focus on how AI augments roles.

Python Basics Mistakes

4. "Using = instead of == in comparisons"
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. "Strings and numbers auto-convert"
"5" + 3 → TypeError! Python doesn't auto-convert between strings and numbers like JavaScript.
✓ Explicitly convert: 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.
6. "Modifying a list while iterating over it"
for item in my_list: my_list.remove(item) — skips elements and produces unexpected results.
✓ Create a new list instead: 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.
7. "Using mutable default arguments"
def add_item(item, lst=[]): lst.append(item); return lst — the default list is shared across all calls!
✓ Use None as default: 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.
8. "Confusing is and =="
Using is to compare values: if x is 5: may work for small integers but fails for larger ones.
✓ Use == 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.
9. "Forgetting Python is 0-indexed"
Expecting my_list[1] to return the first element.
✓ Python uses 0-based indexing. 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.
10. "IndentationError: not understanding Python's whitespace rules"
Mixing tabs and spaces, or forgetting to indent after if, for, def, etc.
✓ Python uses indentation (not braces) to define code blocks. Use 4 spaces consistently (Colab does this automatically). Never mix tabs and spaces. Set your editor to convert tabs to spaces.
💡

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.