Day 2:Python From Zero — Variables, Memory References, Primitive Types & Strings
Battle-tested daily lesson note • 100% runnable code, interview Q&A, test suite & interactive quiz
Week 1 — Day 2: Python From Zero — Variables, Memory References, Primitive Types & Strings
Mentor's Note (10+ YOE Staff AI Engineer POV): Why do we study variables, memory addresses (
id()), and strings on Day 2?
- For Complete Beginners: You learn how to store numbers, text, and true/false values, format strings with
f"...", and slice text[start:stop:step].- For Senior AI Engineers: Large Language Models are literally text-in, text-out machines. Before you send text to an LLM or create vector embeddings, 50% of your job is cleaning messy strings, stripping sensitive PII (emails, phone numbers, API keys), normalizing whitespace, and estimating token counts (
1 token ≈ 4 characters). Plus, interviewers LOVE asking how Python stores variables in memory (object references vs boxes) and what immutability means!
Part 1: How Python Actually Executes Code & Stores Variables in Memory
1.1 Is Python Compiled or Interpreted? (Interview Classic!)
When you run python script.py, two steps happen inside CPython (the standard Python engine written in C):
- Compilation to Bytecode (
.pyc): Python first translates your human-readable.pysource code into low-level Bytecode instructions (which is why you see__pycache__/folders appear!). - Python Virtual Machine (PVM): The PVM interpreter loop reads those bytecode instructions one by one and executes them on your CPU.
1.2 Variables Are Labels (References), NOT Boxes!
In languages like C, a variable int x = 10 is a physical box in memory holding 10.
In Python, everything is an Object in RAM, and a variable name is just a sticky note (pointer/reference) attached to that object!
x = 1000
y = x # Does NOT copy 1000! Both `x` and `y` point to the EXACT SAME object in RAM!
print(id(x) == id(y)) # True! `id()` shows the memory address in RAM.
Part 2: The 5 Primitive Data Types in Python
| Data Type | Python Keyword | Examples | Mutable or Immutable? | How AI Engineers Use It |
|---|---|---|---|---|
| Integer | int | 42, 0, -500, 1_000_000 | Immutable | Counting tokens (prompt_tokens = 1520), HTTP status codes (200), loop counters. |
| Floating Point | float | 0.15, 3.14159, 1e-5 | Immutable | LLM temperature = 0.0, learning rates (1e-4), cosine similarity scores (0.892), USD cost (0.00045). |
| String (Text) | str | "Hello", 'GPT-4o', """Multi-line prompt""" | Immutable | System prompts, user queries, Markdown runbooks, JSON payloads, log lines. |
| Boolean | bool | True, False | Immutable | Schema flags (covered_by_doc = True), guardrail checks (is_safe = False). |
| None (Null) | NoneType | None | Immutable | Representing missing optional values (api_key = None, error_message = None). |
[!WARNING] Floating-Point Math Trap (
0.1 + 0.2 != 0.3): Because computers storefloatnumbers in binary (base-2) fractions (IEEE 754 standard), running0.1 + 0.2in Python outputs0.30000000000000004! AI Engineering Rule: When calculating token costs in USD (e.g.,$0.000150), always useround(cost, 6)or Python'sdecimal.Decimalbefore asserting equality in tests!
Part 3: Mastering Strings, f-strings, and Slicing [start:stop:step]
3.1 String Creation & Multi-Line Prompts
In AI Engineering, we use triple quotes ("""...""") every single day to write multi-line System Prompts:
model_name = "gemini-2.5-flash"
max_words = 100
# An f-string (formatted string literal) injects variables directly inside {braces}:
system_prompt = f"""You are a Senior SRE Incident Responder running on {model_name}.
Answer strictly using the provided runbook in under {max_words} words."""
3.2 String Indexing & Slicing ([start : stop : step])
Every character in a string has a positive index (starting at 0 from the left) and a negative index (starting at -1 from the right):
String : " P Y T H O N "
Index : 0 1 2 3 4 5
Negative: -6 -5 -4 -3 -2 -1
text[0]'P'(First character)text[-1]'N'(Last character)text[0:3]ortext[:3]'PYT'(Starts at index0, stops BEFORE index3!)text[2:]'THON'(From index2to the end)text[::-1]'NOHTYP'(Reverses the entire string! Step of-1walks backward)
3.3 The 8 String Methods Every AI Engineer Uses Daily
| Method | Example | Output | Why We Use It in AI Pipelines |
|---|---|---|---|
.strip() | " hello \n ".strip() | "hello" | Removes leading/trailing spaces and newlines from messy user prompts or LLM outputs. |
.lower() / .upper() | "Error".lower() | "error" | Normalizing text to lowercase before keyword matching. |
.startswith() | "sk-proj-123".startswith("sk-") | True | Checking API key prefixes or Markdown headers (line.startswith("## ")). |
.endswith() | "runbook.md".endswith(".md") | True | Filtering .md, .pdf, or .json files during RAG ingestion. |
.replace(old, new) | "a b".replace(" ", " ") | "a b" | Replacing placeholders or redacting sensitive substrings. |
.split(sep) | "a,b,c".split(",") | ['a', 'b', 'c'] | Breaking a paragraph into words (.split()) or lines (.splitlines()). |
"sep".join(list) | " ".join(["AI", "Pro"]) | "AI Pro" | Fast O(n) way to combine chunks of text into a single prompt string! |
.find(sub) / in | "ERR" in "FATAL ERR" | True | Fast substring check inside server logs. |
Part 4: Hands-On Lab — Building an AI Prompt & Log Sanitizer (text_sanitizer.py)
Before sending server logs or customer messages to an external LLM API, a production AI system must:
- Normalize messy whitespace (saving up to 20% on token costs!).
- Redact sensitive PII (emails, IPv4 addresses, and secret API keys) so confidential data isn't leaked to third-party LLM providers.
- Estimate the token count (
1 token ≈ 4 charactersin English) and calculate the estimated API cost.
Check out src/text_sanitizer.py (in Tab 2: Codes — click Run in Browser to execute) and run it now:
# Run Day 2 Prompt & Log Sanitizer script:
python week01_computer_terminal_git_python_basics/day02_python_variables_types_strings_math/src/text_sanitizer.py
# Run Day 2 Automated Unit Tests:
python -m unittest discover -s week01_computer_terminal_git_python_basics/day02_python_variables_types_strings_math/tests -v