
This course includes our updated coding exercises so you can practice your skills as you learn.
See a demo
Overview: A narrative introduction set in the year 2049—the dawn of Artificial General Intelligence (AGI).
Key highlights:
Follow the story of Triangle, a young developer from New Seoul-7 facing the overnight collapse of the junior tech market.
Discover the origins of his coding journey, starting from a foundational Python course he took at age 13.
Set the stage for "CTF Matrix Hack"—the exact course that laid the groundwork for everything to come.
A narrative introduction to the course. Triangle—a developer who wants to be on the side that patches vulnerabilities, not exploits them—discovers that every path in cybersecurity starts with one fundamental step: learning to code.
Key Highlights:
Direct Access: One author. No team, no marketing—your feedback goes straight to the source.
Community-Driven: Your comments, questions, and insights directly shape future lessons.
Leave Your Mark: Rate the course, drop a comment, ask questions, and share the link.
Module 01 — Prologue | Lesson 1: Python Basics
This lesson is your first step into the Matrix. Before building AI agents, writing RAG pipelines, or orchestrating multi-agent systems — you need to speak the language. This lesson covers the Python fundamentals that every AI engineer relies on daily.
What you'll learn:
Variables as references — not boxes. Understand how Python actually stores objects in memory and why this matters when your code scales
Core data types — int, float, str, bool — with a practical cheat sheet and type casting rules
f-strings — the clean, fast, readable way to format output (and why concatenation is a bad habit)
Arithmetic and logical operators — including the tricky ones: //, %, **, and operator precedence
User input — how input() always returns a string and how to safely convert it
== vs is — one of the most common beginner mistakes, explained with memory diagrams
Extra deep dives for the curious:
CPython Integer Caching — why 256 is 256 is True but 257 is 257 is False
Float precision trap — why 0.1 + 0.2 != 0.3 and how to fix it with math.isclose()
Special values: None, float('inf'), float('nan')
Hands-on exercises:
Easy — Signal Decoding — variables, arithmetic, f-strings, boolean logic
Medium — Temperature Converter — input(), type casting, formulas, try/except
Hard — Hacking Calculator — full mini-app with loops, error handling, and type inspection
By the end of this lesson you'll have a solid mental model of how Python manages memory — a foundation that will matter when we get to agents, chains, and production systems.
The first real lesson of "CTF Matrix Hack." Triangle opens the terminal and starts from absolute zero.
Key Highlights:
Variables: Name tags pointing to objects in memory, not physical boxes.
Four Basic Types: int, float, str, and bool.
Operators: Arithmetic, comparison, and logical operations.
Interaction & Formatting: Using f-strings for clean output and input() for user interaction.
Anti-Pattern: == vs is—a classic trap every beginner falls into.
Extra Deep Dive: Integer caching, the floating-point trap, None, inf, nan, and the mysterious ... (ellipsis).
Module 01 — Prologue | Lesson 2: Conditionals and Loops
The node is locked. To break through, your code needs to make decisions and repeat actions automatically. This lesson covers the control flow tools that form the backbone of every Python program — and every AI agent built on top of it.
What you'll learn:
if / elif / else — how Python evaluates conditions top to bottom and stops at the first match, with real branching logic examples
Ternary operator — writing simple conditions in a single readable line
Truthy and Falsy values — why 0, "", [], {}, and None all behave like False in conditions, and how to write idiomatic checks
The for loop — iterating over lists, strings, and ranges, plus enumerate for clean index access
The while loop — running until a condition is met, with proper exit logic to avoid infinite loops
break and continue — taking control mid-loop: stop searching when found, skip what doesn't fit
Common anti-patterns covered:
if x == True — why this signals inexperience and how to fix it
range(len(list)) — the clunky way to loop with an index, and why enumerate is better
if len(data) == 0 — versus the idiomatic if not data
Extra deep dives:
for...else and while...else — the hidden loop construct almost nobody uses, but should
try...else — separating dangerous code from safe continuation cleanly
Hands-on exercises:
Easy — Access Code Check — for loop with nested conditions, boolean logic
Medium — Password Hack — while loop with attempt counter, break on match
Hard — Password Generator — random, strength validation, while loop for regeneration
By the end of this lesson your code will stop running top to bottom like a script and start making decisions like a program. Next up — lists and tuples.
Triangle learns how to make code think and automate repetitive tasks—the absolute foundation of every hacking script.
Key Highlights:
if / elif / else: Branching logic, ternary operators, and evaluation order.
Truthy and Falsy: What Python actually treats as False (spoiler: it's not just False).
The for loop: Iterating ranges, strings, and lists; using enumerate for index and value.
The while loop: Running until a condition breaks; avoiding infinite loop traps.
break and continue: Taking full control of your loop flow.
Anti-Pattern: Never write if is_active == True—it's a massive red flag.
Extra: The little-known for...else and while...else constructs for cleaner search patterns without flag variables.
Module 01 — Prologue | Lesson 3: Lists and Tuples
Data is flowing through the network — packets, coordinates, signal codes. To work with collections of data in Python, you need two fundamental structures: the list and the tuple. This lesson covers how they work under the hood, when to use each, and the patterns that separate clean code from amateur mistakes.
What you'll learn:
Lists — ordered, mutable collections with O(1) index access; how append, remove, pop, and sort behave under the hood and where they're fast or slow
Indexing and slicing — start:stop:step syntax, negative indices, reversing with [::-1], and extracting subsets without loops
Tuples — immutable sequences for fixed data: coordinates, configs, multiple return values, and dictionary keys
List comprehension — filtering and transforming collections in a single readable line, without manual loops
Unpacking — assigning tuple elements to variables in one line, including the a, b = b, a swap pattern
When to use which:
Use a list when the collection grows, shrinks, or gets sorted — logs, queues, results
Use a tuple when the data is fixed and shouldn't change — coordinates, function return values, hashable keys
Anti-patterns covered:
Mutating a list during iteration — why elements get skipped and how comprehension solves it cleanly
result = original.sort() — why this returns None and how sorted() differs
Extra — interview question:
sort() vs sorted() — in-place mutation versus returning a new list, a classic trap in technical interviews
Hands-on exercises:
Easy — Packet Filtering — sort a list, filter via comprehension, print count
Medium — Finding the Key Packet — index(), slicing around a found element, edge case handling
Hard — Traffic Analyzer — min, max, average, top-5 via slice, above-average filter using only built-ins
Next up — dictionaries and sets.
Triangle digs into the Matrix's data core and learns the two most essential sequence types in Python.
Key Highlights:
Lists: Ordered, mutable collections; append, pop, remove, sort.
Indexing & Slices: [start:stop:step], negative indices, reversing.
Tuples: Immutable sequences; when to use [] vs (); unpacking and value swapping.
List Comprehension: Filter and transform in a single readable line.
Anti-Pattern: Never mutate a list while iterating over it.
Extra: sort() vs sorted(), tuple unpacking in loops, print(*list, sep='\n').
Module 01 — Prologue | Lesson 4: Dictionaries and Sets
The network has nodes, IDs, connections, and overlaps. To map it efficiently, you need structures that give you instant lookup by name and fast membership checks. This lesson covers Python's two hash-based structures — the dictionary and the set — and the patterns that make them powerful.
What you'll learn:
Dictionaries — hash tables with O(1) key access; how keys are hashed, why only hashable types qualify, and why insertion order is preserved since Python 3.7
Safe key access — why d[key] raises KeyError and how .get(key, default) protects you
keys(), values(), items() — iterating over a dictionary cleanly, and dict comprehension for building new mappings with filters
Sets — unique elements, O(1) membership checks, and the full set theory toolkit: intersection &, union |, difference -, symmetric difference ^
add and discard — mutating a set safely without raising errors on missing elements
When to use which:
dict — when you need to look up a value by name or key
set — when you need uniqueness or fast in checks with no associated value
list — when order matters and duplicates are allowed
Anti-patterns covered:
Mutating a dictionary during iteration — why Python raises RuntimeError and two correct alternatives: comprehension or iterating over list(data.keys())
{} for an empty set — this creates an empty dict, not a set; use set() instead
Hands-on exercises:
Easy — Node Map — update nested dict values, filter with dict comprehension
Medium — Network Analysis — set operations, build a mapping of which network each ID belongs to
Hard — Frequency Analyzer — word count from text, case normalization, top-5 with sorted(key=...)
Next up — functions.
Triangle infiltrates the Matrix's data vault and learns how to map the network using fast lookups and unique collections.
Key Highlights:
Dictionaries: Instant O(1) lookups by key; safe access using .get().
Dict Comprehension: Filtering and transforming data into dictionaries in a single readable line.
Sets: Ensuring uniqueness and performing set theory operations (intersection, union, difference).
Anti-Pattern: The fatal trap of modifying a dictionary while iterating over it.
Extra Deep Dive: Hashability rules, frozenset, and the incredibly useful collections.defaultdict.
Module 01 — Prologue | Lesson 5: Functions
Manual, repetitive code is slow and fragile. Functions are how you turn a sequence of actions into a reusable, testable, nameable unit. This lesson covers everything from basic def syntax to decorators — the tools that power every Python library, framework, and AI agent you'll work with in this course.
What you'll learn:
def and return — defining functions, writing docstrings, and understanding why a function without return silently yields None
Parameter types — positional, keyword, default values, *args for variable positional arguments, and **kwargs for variable keyword arguments
Scope and the LEGB rule — how Python resolves variable names: Local → Enclosing → Global → Built-in, and why using global inside functions is an anti-pattern
Lambda functions — anonymous single-expression functions for sorted(key=...), filter(), and map(), and when to use a regular def instead
Decorators — wrapping functions to add logging, timing, and access control without modifying the original code
Anti-patterns covered:
Mutable default arguments — why def f(items=[]) is one of Python's most notorious traps: the list is created once at definition time and shared across all calls. Fix: use None as the sentinel and create the object inside the function
global variables — passing data via arguments and returning it via return is always cleaner
Extra pattern:
Functions are first-class objects in Python — they can be passed as arguments, stored in variables, and returned from other functions. This is the foundation of decorators and higher-order functions used throughout LangChain and LangGraph
Hands-on exercises:
Easy — Vulnerability Calculation — arithmetic, conditionals, default parameters
Medium — Packet Analyzer — returns a dictionary with min, max, avg, count, and filtered large packets; handles empty input
Hard — Logger Decorator — @log_call that prints function name, arguments, result, and execution time via time.time()
Next up — exceptions.
Manual hacking is too slow. Triangle learns to write reusable commands—the core building blocks of any real script.
Key Highlights:
Functions: def, return, and naming conventions (always start with a verb).
Parameters & Arguments: Positional, keyword, defaults, *args, and **kwargs.
Scope (LEGB): Local → Enclosing → Global → Built-in; why global is a strict anti-pattern.
Lambda Functions: For clean one-liners in sorted(), filter(), and map().
Anti-Pattern: Mutable default arguments—one of Python's sneakiest traps.
Decorators: Wrap any function with logging, timing, or access checks using @.
Extra: Keyword-only arguments with * and positional-only arguments with /.
Module 01 — Prologue | Lesson 6: Exception Handling
Every real system fails. Files go missing, users enter garbage, network calls time out, APIs return unexpected data. This lesson teaches you to write code that survives failure — catching the right errors, communicating them clearly, and cleaning up resources no matter what happens.
What you'll learn:
try / except / else / finally — the full exception handling structure: risky code in try, specific handlers in except, success path in else, guaranteed cleanup in finally
EAFP over LBYL — Python's philosophy: act first and handle failure, rather than checking every precondition before acting. Fewer states, less redundancy, more idiomatic code
Common exception types — ValueError, TypeError, ZeroDivisionError, IndexError, KeyError, FileNotFoundError — when each occurs and how to handle them specifically
raise — throwing exceptions deliberately for validation logic, with clear, informative messages for the caller
Custom exceptions — building a module exception hierarchy with a base class and specific subclasses that carry structured data like error codes and context fields
Anti-patterns covered:
Bare except: — catches everything including KeyboardInterrupt and SystemExit, silently swallows bugs, and makes debugging nearly impossible. Always name the exception type
except Exception: pass — slightly better but still dangerous; at minimum, log the error or return a meaningful default
The rule: every except block must do something — log, return a fallback, or re-raise
Patterns you'll use throughout this course:
try / except blocks inside LangChain tools and AG2 agents to handle API failures gracefully
raise ValueError for input validation at agent boundaries
finally for closing files, database connections, and HTTP sessions
Hands-on exercises:
Easy — Safe Input — wrap input() calls with ValueError and ZeroDivisionError handlers, finally for logging
Medium — Robust Log Parser — parse a mixed list of strings, skip invalid entries, return structured stats with error count and average
Hard — Retry Decorator — @retry(max_attempts=3, delay=1) that logs each attempt, sleeps between retries, and re-raises after exhausting attempts
Next up — working with files.
Deep in the Matrix, system agents start pushing back—and they show up as errors. Triangle learns to write resilient code that doesn't crash under pressure.
Key Highlights:
EAFP vs LBYL: Why Python favors "try it and catch the error" over "check before every step."
try / except / else / finally: The full block structure and when to strictly use each part.
Common Exceptions: ValueError, TypeError, ZeroDivisionError, KeyError, FileNotFoundError, and more.
raise: How to manually trigger exceptions for input validation.
Custom Exceptions: Building an exception hierarchy (HackError → AccessDeniedError) for meaningful error messages.
Anti-Pattern: The bare except: pass—Python's silent bug killer.
Extra Deep Dive: The exception hierarchy from BaseException, and exception chaining using raise ... from.
Module 01 — Prologue | Lesson 7: Working with Files
Data in memory disappears when the process ends. Files are how programs persist state, share results, and communicate across runs. This lesson covers the full toolkit for reading and writing text, CSV, and JSON — the three formats you'll encounter constantly when building AI pipelines, logging agent outputs, and storing configuration.
What you'll learn:
with open() — the only correct way to work with files: the context manager guarantees the file closes even if an exception occurs mid-read
File modes — r, w, a, x, r+: what each does, which ones create files, and why w is dangerous (it silently erases existing content)
Reading strategies — read() for small files, readlines() for a list of strings, for line in f for large files that shouldn't be loaded entirely into memory
Writing — write() and writelines(), the difference between overwrite and append, and why \n must be added manually
CSV with csv.DictWriter / csv.DictReader — reading and writing tabular data as dictionaries, and why newline="" is mandatory on Windows
JSON with json.dump / json.load — saving and loading nested structures with indent for readability and ensure_ascii=False for non-ASCII characters
Anti-pattern covered:
Omitting encoding — Python falls back to the system default: cp1251 on Windows, utf-8 on Linux. The same script breaks on a different machine. Always specify encoding="utf-8" explicitly
Patterns you'll use throughout this course:
Saving agent outputs and pipeline results to JSON
Reading configuration files for LangChain and ADK agents
Logging tool calls and responses to CSV for evaluation datasets
Hands-on exercises:
Easy — Operation Log File — write a list of log dicts to both .txt and .csv, handle PermissionError, read back and verify
Medium — Log Analyzer — parse the CSV, count action frequencies, extract successful entries, save a report to JSON
Hard — DataManager class — save(data, path) and load(path) that detect format by file extension and handle all IO errors gracefully
Next up — object-oriented programming.
Hacked data lives only in RAM—close the program and it's gone. Triangle learns how to save and load data that actually persists.
Key Highlights:
with open(): The only correct way to open files; auto-closes even on error.
File Modes: "r", "w", "a", "x", "r+", and exactly what they do.
Reading: read(), readlines(), and for line in f (the best approach for large files).
Writing: write(), writelines(), and why you must always append \n manually.
CSV: csv.DictWriter and DictReader for handling flat tabular data.
JSON: json.dump and json.load for complex, nested structures.
Anti-Pattern: Skipping encoding="utf-8"—the silent UnicodeDecodeError trap on Windows.
Extra Deep Dive: pathlib—modern, object-oriented path handling.
Module 01 — Prologue | Lesson 8: Object-Oriented Programming
Scripts get you started. Classes take you further. When your codebase grows — multiple agents, tools, memory systems, API clients — you need a way to bundle state and behavior into reusable, testable units. This lesson covers OOP from first principles to the patterns used in every major Python framework.
What you'll learn:
Classes and objects — __init__, self, instance attributes, and the difference between a blueprint and an instance
The four pillars — encapsulation (protect state), abstraction (hide complexity), inheritance (reuse without duplication), polymorphism (duck typing in Python: if it has the method, it works)
Dunder methods — __str__ for human-readable output, __repr__ for developer debugging, __add__ for operator overloading, __eq__ for equality — integrating your class into the Python ecosystem
Inheritance — super().__init__(), method overriding, and isinstance() for type checking across a class hierarchy
Class vs instance attributes — the subtle trap where assigning via self.x creates a new instance attribute instead of modifying the shared class attribute
Inheritance vs Composition:
Use inheritance (is-a) when a subclass genuinely is a specialized version of the parent — StealthVirus is a Virus
Use composition (has-a) when a class contains or uses another — VirusTracker has viruses. Composition is more flexible, less coupled, and easier to change without breaking dependent code
Favor composition — tighter inheritance hierarchies break easily when the parent changes
Anti-pattern covered:
God Class — one class that scans nodes, hacks systems, saves logs, sends emails, and renders UI. Violates the Single Responsibility Principle and makes every part untestable. Break it into focused classes: one class, one reason to change
Why this matters for AI engineering:
LangChain tools, LangGraph nodes, and ADK agents are all implemented as classes. Understanding __init__, method overriding, and composition is the prerequisite for reading and extending framework source code confidently.
Hands-on exercises:
Easy — Virus Class — __init__, attack(), toggle(), __str__
Medium — Inheritance + Tracker — Trojan(Virus) with disguise_level, VirusTracker with add, launch_attacks, get_stats
Hard — RPG System — Character base class with Warrior, Mage, Rogue subclasses and a Battle class that logs moves and declares a winner
Next up — the final mission.
Deep in the Matrix's core, simple scripts no longer cut it. Triangle learns to build sophisticated digital weapons using the full OOP toolkit.
Key Highlights:
The Four Pillars Encapsulation, Abstraction, Inheritance, and Polymorphism, plus the power of duck typing.
Classes Mastering class, __init__, and self; understanding attributes vs. methods.
Magic (Dunder) Methods Tapping into __str__, __repr__, __add__, __eq__, and the broader ecosystem.
Inheritance Implementing super().__init__(), method overriding, and isinstance() checks.
Composition vs. Inheritance "Has-a" vs. "is-a" relationships; why composition is often the superior architectural choice.
Class vs. Instance Attributes Navigating a frequent source of logic bugs.
Anti-Pattern The "God Class"—avoiding the trap of a single class that does everything.
Extra Tech Leveraging @property, __slots__, and @dataclass.
Module 01 — Prologue | Lesson 9: Final Mission — Matrix Core Hacker
Nine lessons. One system. This is where everything comes together. Instead of isolated exercises, you'll build a complete, working program from scratch — a network hacking simulator that uses every concept from the module in its proper context.
What you'll build:
MatrixCoreHacker — a fully functional controller that manages a network of nodes, deploys viruses, runs probabilistic attacks, analyzes network state, and persists all data to files.
System architecture:
Node — data model with node_id, signal_strength, security_level, and is_hacked state
Virus — attack model with probabilistic attack(node) logic based on power vs. security level
StealthVirus(Virus) — subclass that multiplies attack chance by a stealth_factor, demonstrating inheritance and polymorphism
MatrixCoreHacker — main controller using a dict for nodes, list for viruses, set for active node tracking, and list for logs
Every module concept in use:
Data types — Node and Virus attributes
Conditions & loops — hacking logic, auto-hack
Lists, tuples — viruses, logs
Dictionaries, sets — nodes, active_nodes
Functions, lambda — methods, analytics filters
Exceptions — input validation, IO errors
Files, CSV, JSON — load_nodes_from_csv, save_report_json
OOP — Node, Virus, StealthVirus, MatrixCoreHacker
Build sequence:
Node and Virus data classes with __str__ and probabilistic attack()
StealthVirus subclass overriding attack() with stealth multiplier
MatrixCoreHacker controller with add_node, hack_node, auto_hack, and internal _log()
analyze_network() returning total, hacked count, active viruses, average signal and security
File IO — load_nodes_from_csv, save_logs, save_report_json — all wrapped in specific exception handlers
Quality requirements enforced throughout:
Every class has __str__ or __repr__
Every file operation uses with open() and encoding="utf-8"
No bare except: — every handler names a specific exception type
No duplication — shared logic lives in methods
snake_case for variables and functions, PascalCase for classes
This is the foundation. Web, AI agents, and automation start in the next module.
Everything from nine lessons converges into one project. Build a complete, coherent system—not a collection of scripts.
Goal: A console app that manages network nodes, deploys viruses, analyzes the network, and logs everything.
Architecture: Node, Virus, StealthVirus, and MatrixCoreHacker controller—all connected.
New Tools: random, datetime, and PermissionError.
5 Build Steps: Data classes → controller → automation + analytics → file I/O → demo.
Quality Checklist: __str__/__repr__, with statement + encoding, specific except blocks, no code duplication, lambda usage, and sets.
This is the closing narrative of the Matrix Coders Python course.
This course contains the use of artificial intelligence.
Step into the terminal. Decode the Matrix. Master pure Python from absolute zero through an immersive, story-driven crash course designed to forge the solid coding foundation required for modern software and AI Engineering.
The Story: Jacking Into the Matrix
Set against a gritty cyberpunk narrative, you follow Triangle—a developer navigating the digital underground of New Seoul-7. To understand how systems work, patch vulnerabilities, and build autonomous software, you start from the ground up: one line of code at a time.
No dry academic lectures. No copy-pasting without comprehension. Every lesson places you in front of the terminal to solve tangible problems, crack ciphers, and architect robust programs.
Prequel to the Flagship Bootcamp
This course serves as the official standalone Prequel & Foundation Module (Module 0) of our flagship bootcamp: AI Engineer Bootcamp 1337 | AI Automation Agent RAG Finetune
Before building autonomous multi-agent swarms, complex RAG pipelines (Vector, Hybrid, Graph), MCP toolkits, fine-tuning LLMs with Unsloth, and orchestrating agents with LangChain, LangGraph, AG2, and Google ADK, you need unshakeable mastery over core Python semantics, OOP architecture, and data pipelines. This course provides that exact launchpad.
What You Will Build and Master
Core Language Mechanics: Primitive types (int, float, str, bool), memory object references, type casting, and modern f-string formatting.
Flow Control & Automation: Dynamic branching (if/elif/else), ternary expressions, truthy/falsy evaluation, and for/while automation with enumerate, break, and continue.
Data Collections & Structures: Practical usage of lists, immutable tuples, hash-map dictionaries, and unique sets.
Functions & Functional Tools: Parameter architectures (*args, **kwargs), LEGB variable scoping, lambda one-liners, generators, and function decorators.
Defensive Programming: The Pythonic EAFP paradigm, fine-grained try/except/else/finally error handling, custom exception hierarchies, and clean tracebacks.
File I/O & Data Persistence: Context managers (with), modern pathlib, plain text manipulation, and structured CSV / JSON processing.
Object-Oriented Programming (OOP): Encapsulation, inheritance, polymorphism via duck typing, magic dunder methods (__str__, __repr__, __add__), dataclasses, and composition over inheritance.
Capstone Project — Matrix Core Hacker: A complete, multi-tiered console application combining OOP hierarchy, automated node scanning, targeted virus deployment, error resilience, and automated JSON/CSV reporting.
How Each Lesson Is Structured
Every single lesson follows a battle-tested engineering blueprint:
The Problem & Real-World Analogy: Why this concept exists and how it behaves under the hood.
Working Code & Anti-Patterns: What clean code looks like vs. the sneaky traps beginners fall into.
Multi-Tiered Assignments: Level 1 (guided code skeleton), Level 2 (algorithmic problem), and Level 3 (open-ended architectural build).
Deep Dive Extra: Memory optimization, caching, and Python internals.
Your Next Step in AI Engineering
Once you finish this course and conquer the Matrix Core Hacker capstone project, you will be fully prepared to step directly into our comprehensive flagship program: AI Engineer Bootcamp 1337 | AI Automation Agent RAG Finetune.
Plug into the terminal, master the fundamentals, and start building your engineering foundation today!