Week 1 • Day 2100% FREE

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?

  1. For Complete Beginners: You learn how to store numbers, text, and true/false values, format strings with f"...", and slice text [start:stop:step].
  2. 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):

  1. Compilation to Bytecode (.pyc): Python first translates your human-readable .py source code into low-level Bytecode instructions (which is why you see __pycache__/ folders appear!).
  2. 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!

python
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 TypePython KeywordExamplesMutable or Immutable?How AI Engineers Use It
Integerint42, 0, -500, 1_000_000ImmutableCounting tokens (prompt_tokens = 1520), HTTP status codes (200), loop counters.
Floating Pointfloat0.15, 3.14159, 1e-5ImmutableLLM 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"""ImmutableSystem prompts, user queries, Markdown runbooks, JSON payloads, log lines.
BooleanboolTrue, FalseImmutableSchema flags (covered_by_doc = True), guardrail checks (is_safe = False).
None (Null)NoneTypeNoneImmutableRepresenting missing optional values (api_key = None, error_message = None).

[!WARNING] Floating-Point Math Trap (0.1 + 0.2 != 0.3): Because computers store float numbers in binary (base-2) fractions (IEEE 754 standard), running 0.1 + 0.2 in Python outputs 0.30000000000000004! AI Engineering Rule: When calculating token costs in USD (e.g., $0.000150), always use round(cost, 6) or Python's decimal.Decimal before 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:

python
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):

text
String : " P Y T H O N " Index : 0 1 2 3 4 5 Negative: -6 -5 -4 -3 -2 -1
  • text[0] →\rightarrow 'P' (First character)
  • text[-1] →\rightarrow 'N' (Last character)
  • text[0:3] or text[:3] →\rightarrow 'PYT' (Starts at index 0, stops BEFORE index 3!)
  • text[2:] →\rightarrow 'THON' (From index 2 to the end)
  • text[::-1] →\rightarrow 'NOHTYP' (Reverses the entire string! Step of -1 walks backward)

3.3 The 8 String Methods Every AI Engineer Uses Daily

MethodExampleOutputWhy 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-")TrueChecking API key prefixes or Markdown headers (line.startswith("## ")).
.endswith()"runbook.md".endswith(".md")TrueFiltering .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"TrueFast 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:

  1. Normalize messy whitespace (saving up to 20% on token costs!).
  2. Redact sensitive PII (emails, IPv4 addresses, and secret API keys) so confidential data isn't leaked to third-party LLM providers.
  3. Estimate the token count (1 token ≈ 4 characters in 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:

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