Python Essentials Through a Support Ticket
Python programs transform values through explicit control flow and functions. Backend code receives untrusted input, converts it into trusted domain values, applies rules, and produces an output or error. Learning these basics through one ticket avoids syntax drills disconnected from the system you will eventually build.
What will you be able to do?
- use strings, numbers, booleans, None, lists, dictionaries, and sets;
- write conditions, loops, and small functions;
- distinguish mutation from returning a new value;
- run a module and verify behavior with assertions.
How can a ticket become a Python value?
Create src/supportdesk_ai/tickets.py:
The function validates before constructing the dictionary. It returns a new value instead of changing input owned by another caller.
Use it from a Python shell:
How do collections differ?
- A list preserves order and duplicates.
- A dict maps unique keys to values.
- A set stores unique membership and is ideal for allowed-value checks.
- A tuple is an immutable ordered collection.
Choose based on meaning, not habit. Tickets returned by an API may be a list; one ticket representation may be a dictionary; allowed roles may be a set.
Why does this matter in AI-native systems?
Model output may look plausible while containing missing keys, unsupported labels, or unexpected types. Plain collection operations help you inspect data, but production boundaries will use Pydantic models so invalid model output cannot quietly become application state.
Common mistakes
- Using a mutable list as a default argument; use None and create a list inside, or use a model factory.
- Catching every error and returning None; preserve meaningful failure categories.
- Mutating a dictionary passed by another layer; make ownership explicit.
- Treating truthiness as validation; 0, False, "", and None have different meanings.
AI Pair-Programmer Prompt
Exercise
Add add_tag(ticket, tag) that normalizes the tag to lowercase, rejects an empty tag, prevents duplicates, and returns a new ticket dictionary without mutating the original.
Acceptance criteria: assertions prove normalization, uniqueness, rejection, and unchanged original input.
Knowledge check
- Which collection is best for allowed-value membership?
- Why validate before constructing a ticket?
- What is the risk of hidden mutation?
Answers
- A set.
- Invalid state should never be created.
- Other code holding the same object can change unexpectedly, making behavior hard to reason about.
Completion checklist
Primary references