→ From Coder to Shipper
From Coder to Shipper · Foundations

Python Basics

The glue language of your server: how scripts run, the data they hold, and the patterns you'll recognize in every line of backend code.

← / → to navigate · EN/VI switch below

Big picture

Python is the glue on your server

Everything behind your frontend — the app, the tooling, the scripts — is usually Python. You'll read it, judge it, and steer the AI that writes it.

Your web app is Python

Flask — the framework this course ships with — is a Python library. Every page your app serves is decided by Python code.

The glue language

Python connects the pieces: takes a web request, reads data, calls other tools, writes files. It's the connective tissue of a backend.

AI writes Python fluently

Python is among the languages AI generates best. You don't type it from memory — you ask, get code, and check it.

Your job: recognize & tweak

This deck gives you the mental model: what each construct is for. That's what lets you review AI code and nudge it in the right direction.

How you'll code in this course

You don't type — you recognize, ask, verify

AI writes the Python. Your skill is the three moves that make AI code trustworthy.

Recognize the shape

You don't type from memory. You look at code — yours or the AI's — and know what each block is for: a function, a loop, a data read.

Ask for an explanation

Any line you can't recognize → paste it to the AI: 'what does this do?' Explanations are free; recognition is the skill.

Verify the output

The best check is running it: print what you expect, read the result, compare. Output is the truth — not the code, not the AI's confidence.

01
Part 1

Running Python

Two doors into the language — and what happens when things break.

Part 1 · your first script

A .py file is just instructions, top to bottom

Variables store values in labelled boxes; print() shows them. That's the entire vocabulary of a beginner script.

hi.py
# hi.py — a comment: Python ignores it, humans read it
name = "shipper"           # a variable: a labelled box

print("Hello, " + name)    # send text to the screen
print("Ready to build.")

That's a complete program: a variable and two print calls. Nothing else is required to start.

Part 1 · variables

Variables — labelled boxes

A variable is a name pointing at a value. The name is the label; the value (and its type) can change.

name = value

score = 82 — the name score now points at the value 82. Read it as 'score holds 82'.

Reassignment is normal

score = 90 later just moves the label to a new value. Boxes aren't fixed — labels are what move.

The type lives in the value

You don't declare types. 82 is an int, "An" is a str, True is a bool — Python knows from the value itself.

Part 1 · running it

Script mode & REPL mode

One command runs a whole file; the same command with no file opens the REPL (Read-Eval-Print Loop) — a live playground for testing one line at a time.

ops@vps — zsh
$ python hi.py
Hello, shipper
Ready to build.
$ python ← no file: opens the REPL
>>> 2 + 2
4
>>> "ab" * 3
'ababab'
>>> exit()
Part 1 · when it breaks

Errors are normal — read the bottom

Every Python error ends in a traceback: a stack of where you were, and the actual problem on the last line.

ops@vps — zsh
$ python hi.py
Traceback (most recent call last):
File "/home/student/hi.py", line 4, in <module>
print(nmae) ← typo in the variable name
NameError: name 'nmae' is not defined
↑ the last line is the answer — everything above is 'where'
Part 1 · reading errors

A traceback, in three moves

You'll paste these into the AI constantly. Knowing the three parts makes you fast at it.

File & line

File "hi.py", line 4 tells you exactly where to look. That's your pointer for targeted tweaks.

The error name

NameError (typo / undefined), KeyError (missing dict key), TypeError (wrong type). The name is a category, not a verdict.

Paste it to the AI

Copy the whole traceback, not just the last line. The stack above shows the path that led there.

02
Part 2

Data: what Python actually holds

A program is mostly data in motion. Five small types cover nearly everything — and two of them (list, dict) are the stars.

Part 2 · the five types

str, int, float, bool — and the big two

You'll meet these in every backend. str/int/float/bool are the atoms; list & dict are how data is actually organized.

TypeExampleWhat it's for
str"hello"Text: names, messages, URLs
int42Whole numbers: counts, ids, ports
float3.14Decimal numbers: prices, scores
boolTrue / FalseA yes/no switch: is_active, is_admin
list["a", "b"]An ordered set of things — tasks, results, users
dict{"name": "An"}Label → value pairs — one record: a user, a request, a config
Part 2 · the big two

List & dict look like JSON — because they are

Every API response, config file and database row arrives as JSON. Python's list and dict read it natively — no translation layer.

data.py
# A list: ordered things
tasks = ["design", "code", "test", "ship"]

# A dict: labelled values (a record)
user = {
    "name": "An",
    "role": "designer",
    "active": True,
}

If you've seen JSON, you already know this: dict = the JSON object {…}, list = the JSON array […].

Part 2 · the classic mix-up

= versus ==

One is a verb, the other is a question. Confusing them is one of the most common things to catch in AI (and human) code.

= — assign

Put a value in a box: name = "An". The right side is computed first, then stored. It changes state.

== — compare

Ask a question: name == "An" → True or False. It changes nothing — it just answers, and the answer is a bool.

Part 2 · strings

Strings — text you can actually work with

Strings are the most common data in a web app. A handful of operations cover the daily work.

len(s) — how long

len("hello") → 5. Counts the characters.

"in" — is it inside?

"ell" in "hello" → True. Substring check; it works on lists too (next slide).

s.upper(), s.lower()

"An".upper() → "AN". Case changes for matching and display.

s.split() — cut into a list

"a b c".split() → ["a", "b", "c"]. Text in, list out — the text-to-data bridge.

Part 2 · working with values

Reach in: indexes, lengths, comparisons

Data isn't only created — you reach into it. These three moves show up in almost every loop you'll ever read.

values.py
tasks = ["design", "code", "ship"]
print(len(tasks))         # 3
print(tasks[0])           # design — counting starts at 0
print("design" in tasks)  # True

age = 29
print(age > 18)           # True  ← a comparison makes a bool
print(age == 30)          # False

Counting starts at 0, so the first item is index 0 and the last is len − 1. Comparisons (>, <, ==) don't change anything — they produce True/False.

Part 2 · none

None — the honest 'nothing'

Between values and errors, Python has a third state: a legitimate absence.

None = no value

Python's word for 'nothing here'. A function without return gives None; a missing .get() gives None.

Why it exists

It's honest: 'I looked, there's nothing.' Better than crashing, better than faking a value like 0 or "".

Check with is

if value is None: — the standard way to ask 'did we get anything?' before using it.

03
Part 3

Logic

How Python decides and repeats — the shapes you'll recognize in any snippet AI hands you.

Part 3 · the decision

if / elif / else

Don't memorize syntax — recognize the shape: a condition, a colon, an indented block.

grade.py
score = 82

if score >= 90:
    grade = "A"
elif score >= 80:
    grade = "B"
else:
    grade = "C"

print(grade)   # B

Python checks top to bottom and runs the first branch whose condition holds. else catches everything left. Indentation is the grouping — no braces.

Part 3 · the walk

for — walking a collection

The workhorse loop: give it any collection, it hands you the items one at a time.

loop.py
for task in ["design", "code", "ship"]:
    print(task)

for i in range(3):        # range(3) → 0, 1, 2
    print(i)

for walks any collection, one item at a time — a list, or the range(n) 'count from 0' collection. Most loops in real code are for-loops.

Part 3 · the repeat

while — repeat while it holds

The loop you must control: it runs as long as the condition stays true.

retry.py
retries = 3
while retries > 0:
    print("retrying...")
    retries = retries - 1    # runs 3 times

You must move the condition toward false inside the loop. If you forget — infinite loop, and the server stops answering. for handles most jobs; while is the careful one.

Part 3 · combining conditions

and, or, not — combining checks

Real conditions are rarely a single comparison. Three words combine them into English-like tests.

and — both must hold

age >= 18 and active — both sides true, or the whole thing is false. It means 'also'.

or — either is enough

role == "admin" or role == "owner" — at least one true. It means 'either'.

not — flip it

not banned — true when banned is false. It means 'not'. You'll see these three in nearly every if you'll ever review.

04
Part 4

Reuse & everyday moves

Functions, strings, data operations, files, imports — the daily toolkit of a backend.

Part 4 · functions

def — the unit of reuse

A function packages a task: name it, give it inputs, get a result back. Call it as often as you like.

greet.py
def greet(name):              # define: a reusable recipe
    return f"Hello, {name}!"

print(greet("An"))    # Hello, An!   ← call it
print(greet("You"))   # Hello, You!  ← call again

def names the recipe, arguments (name) are the inputs, return hands back the result. The f"…" string inside is the next slide.

Part 4 · strings & notes

f-strings & comments

The two smallest but most visible constructs — you'll spot them on line one of almost every file.

f-string — strings with holes

f"Hi {name}, {n} tasks left" — values drop straight into the text. The #1 way to build messages.

{…} can be any expression

f"{2 + 3}" gives "5". Functions work too: f"{len(tasks)}".

# comments — for humans

Python skips everything after #. AI reads them too — a good comment is a steering wheel for the AI that maintains your code.

Part 4 · everyday moves

Working with lists & dicts

Three moves cover most of the daily work: grow a list, read a dict safely, loop over things.

work.py
tasks = ["design", "code"]
tasks.append("ship")           # grow the list

user = {"name": "An", "role": "designer"}
print(user["name"])            # An
print(user.get("email"))       # None — safe if missing

for t in tasks:                 # loop over items
    print(t)

d["key"] crashes if the key is missing; d.get("key") calmly returns None. Prefer .get() when the key is uncertain — most AI bugs come from missing keys.

Part 4 · the operations table

The list & dict operations you'll see most

Six operations cover the daily work. All of them are methods: data.method().

OperationWhat it does
len(x)Length of a list, dict or string.
x in dataMembership test — is this item or value inside? → True/False.
data.append(v)Add v to the end of a list. Grows it.
d.get(k)Read a dict value; None instead of a crash if the key is missing.
d.keys()The list of a dict's labels. How you loop over a record.
d.items()Label + value pairs, for looping over both at once.
Part 4 · files

Reading a file, at a glance

Files are how a program remembers things between runs — configs, data, logs. The shape below appears in almost every backend you'll touch.

read.py
with open("tasks.txt") as f:    # open, and close for you
    for line in f:               # a file is a list of lines
        print(line.strip())      # remove the newline

open() hands you a file handle; with guarantees it's closed. Line by line, a file is just a list of strings.

Part 4 · writing

Writing a file — the mode letter

Same open/with shape as reading; the only difference is one letter: the mode.

write.py
with open("out.txt", "w") as f:      # w = write, erases first
    f.write("task: design\n")

with open("out.txt", "a") as f:      # a = append, keeps existing
    f.write("task: ship\n")

w starts fresh, a adds on. This is exactly how apps write logs and save data — the same shape you've just learned for reading.

Part 4 · imports

import — pulling in toolboxes

You don't build everything yourself. One line brings in a whole toolbox — Python ships with a huge standard library.

import = a toolbox

import json gives you JSON tools; import math gives you math. One line, whole toolbox — the top of nearly every file.

The json module

json.loads turns a JSON string into dict/list; json.dumps does the opposite. This is how your app talks to the web.

Your app's first line

from flask import Flask — even 'using Flask' is just an import. Every backend you'll read starts with imports.

Part 4 · when things can fail

try / except — fail gracefully

Real data is messy: missing keys, empty files, bad input. Programs that handle it keep running.

safe.py
try:
    value = user["email"]
except KeyError:
    value = "no email"

print(value)

try: attempt the risky part; except: if it fails, do this instead. Programs degrade gracefully instead of crashing — you'll see this around every data read.

Part 4 · it all comes together

One file, every pattern

Nothing new here — just the deck's pieces in one place. Read it top to bottom; you already know every line's job.

mini.py
import json

def summary(raw):
    users = json.loads(raw)      # JSON string -> list of dicts
    active = 0
    for u in users:
        if u.get("active"):
            active = active + 1
    return f"{active} of {len(users)} active"

raw = '[{"name": "An", "active": True}]'
print(summary(raw))              # 1 of 1 active

import, def, json.loads, for, if, .get, len, f-string — the whole vocabulary of this deck, doing real work in twelve lines.

05
Part 5

Python in your app

Everything was preparation for this: your Flask app, the tooling, the scripts — all of it is the pieces you just learned.

Part 5 · no magic

Your Flask app is just these pieces

Now look at this course's own app: a .py file with functions, dicts, files and JSON. Every piece on this slide is in that app.

A route is a function

"GET /slides/python-basics" → Python calls a function → it returns a page. def + return, exactly the greet() slide.

Requests are dicts

Every web request arrives as a labelled bag: query params, form fields, headers. You read it with d.get("key") — the everyday-moves slide.

Data out as JSON

The app reads data (files, database), shapes it into dicts and lists, sends it to your browser as JSON — the list/dict from Part 2.

Files underneath

Settings and data come from files — the open/with shape from Part 4. Python is the connective tissue between the web and the disk.

Part 5 · your workflow

Reading & tweaking code with AI

The daily loop of this course: you and the AI, one code block at a time.

  1. 1

    Scan the shapes

    Before asking anything, look for the patterns: def, for, if, dict, open. You already know what each one is for.

  2. 2

    Ask line by line

    Paste a block and ask 'explain this in simple words.' Compare the AI's answer with your own read — that gap is where learning happens.

  3. 3

    Point, don't dump

    Tweaks work best with a target: 'change this function to also check the email key.' Specifics in, specific changes out.

  4. 4

    Run & check the output

    After any change, run it and look at what it prints or serves. Output right → shape right. Output wrong → paste it back and repeat.

You don't need to write Python by hand. You need to recognize it, judge it, and steer the AI that writes it.
— the course

Variables. Data. Logic. Reuse. That's the language.

Next: your first Flask route — the same Python, now answering the web. Ask the AI to explain any line you don't recognize.