ContentsClose contents
Pre-release
Chapter 4 · Python readiness and development toolsCHAPTER 04

Six-part pre-release for review, with 10 figures, seven tables, and worked exercises using uv 0.13.5 and Python 3.14.9. No Django application is implemented.

Working towards: Plan ready (Chapter 5). A product brief, written requirements, web vocabulary, a checked Python setup, and a proposed architecture. Django is not installed yet. All milestones

CHAPTER FOUR

Python readiness and development tools

Stage 1: Requirements and first project (Chapters 1 to 8)

Prerequisites: basic Python reading, and Chapters 1 to 3 for the product and web context

What you’ll build: worked Python readiness exercises, small practice files, and a checked uv-managed environment running Python 3.14.9.

Why This Matters

Chapter 3 followed a request from a browser to the application and back. From Chapter 6 onward, the code that handles such requests is Python, and Django adds a great deal of its own vocabulary on top. If the language underneath is shaky, every Django error looks mysterious: a missing colon, a misspelled dictionary key, or a function that prints instead of returning can each look like a framework problem.

There is a second kind of trouble that has nothing to do with the language. Sai saves a file, runs it, and sees an old result; Raj installs a package and the import still fails. Both are questions about tools: which file was saved, which folder the terminal is in, and which Python ran. Making those answers visible now prevents that confusion later.

So this chapter does two things. What You Need to Know rehearses the Python the book relies on, on paper, with Otahque-flavoured examples: values and decisions, collections and loops, functions and imports, classes, and reading errors. How We Build It then turns those sketches into saved files, runs them with an identified Python, and finishes with a virtual environment and a readiness check you can repeat.

By the end of the chapter, you will be able to:

  • trace values, comparisons, and decisions in a short Python example;
  • read collections, loops, functions, imports, and simple classes;
  • use an error message to locate a problem;
  • distinguish an editor, a terminal, and the Python interpreter;
  • run a practice file in an isolated environment and explain its result.

You will produce worked readiness exercises and, in the later tools sections, small practice files and a checked local environment. Basic Python is a prerequisite; this chapter helps you identify and repair gaps. Chapters 1 to 3 provide the product and web context. The first Django project still begins in Chapter 6.

PAGE 001

What You Need to Know

New Concept: the Python readiness bridge

What problem exists? Django examples combine Python values, collections, functions, and objects. A gap in one of these can make an otherwise small example difficult to follow.

What did people do before? A reader might copy a complete example and inspect it only after an error. Here we first predict what a smaller example does.

What is the bridge? A review of prerequisite Python through four groups: values and decisions, collections and loops, functions and imports, and classes and errors.

Why review them together? Their results connect: a collection supplies a value to a function, and an object keeps related values and behaviour together.

Now let’s trace the examples on paper, compare the answers, and later run saved versions in How We Build It.

Values, names, and decisions

Sam prepares an event for Otahque. He needs a private draft before visitors can read the published event. The product requirements distinguish those two states. How can a small Python example represent that distinction and choose an appropriate message?

For this section, read and trace the examples on paper. No installation, file, shell command, or existing application checkpoint is required. The examples use invented values and do not connect to Otahque. How We Build It will show how to save and run a Python file. Your visible result now is a prediction you can compare with each worked answer.

Give a value a meaningful name

A value is a piece of data, such as the event title or a number. A variable name lets a program refer to a value. Read the following lines from top to bottom:

event_title = "Python Evening"
capacity = 12
is_published = False

Each line is an assignment. The equals sign binds the name on its left to the value on its right. Here, event_title refers to text, capacity refers to a whole number, and is_published refers to a yes-or-no value. The underscores make multiword names readable without spaces.

Text is called a string; the quotation marks delimit it in the source code. A whole number is an integer. A Boolean is one of the two values True and False, written with those capital letters and without quotes. These kinds of values are called types. The type matters when we ask Python to calculate or compare.

The invented capacity of 12 is practice data, not a selected limit for Otahque. Likewise, the name is_published helps explain our intent but cannot enforce the publication rules by itself.

Que. 1 Are False and "False" the same value?

Flip to check your answerFold answer back

Answer. No. False is a Boolean; "False" is a string containing five letters. Quotation marks change how Python interprets the value. Use the Boolean when the example needs an actual yes-or-no fact, rather than text that happens to spell its name.

Separate assigning from comparing

An expression is code that produces a value. For example, capacity - 1 produces the number one below capacity. A comparison asks a question and produces True or False. Python uses == to ask whether two values are equal; a single = performs assignment.

capacity = 12
print(capacity == 12)
print(capacity == 8)

print is a built-in function: a named operation Python already provides. The parentheses contain what we ask it to display. Here Python evaluates each comparison first, then prints its result. Expected output, on two separate lines:

True
False

A program printing True has answered this one comparison. It has not proved that an event is valid, that Sam may manage it, or that registration is open. Those are separate product questions. Keeping each question precise will matter when we later translate the PRD into checks.

Que. 2 What is the difference between capacity = 12 and capacity == 12?

Flip to check your answerFold answer back

Answer. The first binds capacity to 12. The second compares its current value with 12 and produces a Boolean result. A comparison does not change capacity.

Common Error: = where you meant ==

A single equals sign assigns; a double equals sign compares. Writing if capacity = 12: is a SyntaxError, because an if needs a question, not an assignment. When a condition fails to parse, check each comparison for a missing second =.

Follow one branch

A condition is an expression used to choose what happens next. In this example, the condition is the Boolean value named is_published. The if statement selects the first indented block when that value is True; otherwise, else selects the second block.

is_published = False

if is_published:
    print("Public event")
else:
    print("Private draft")

The colon introduces a block. The four spaces before each print show that it belongs inside that branch. Indentation is part of Python’s structure, not decoration. The if and else lines line up; their contents sit one indentation level further in.

Start with the assigned value: False. Follow the else branch. The expected output is Private draft. Only one of these two messages is printed. Figure 4.1 shows that choice; neither path changes is_published.

A supplied is_published value reaches a True decision. Yes leads to printing Public event; no leads to printing Private draft. Neither path changes the event or grants access.
Figure 4.1 — A Boolean value selects a display message.

Now change only the first line to is_published = True. The condition selects the first branch and the output becomes Public event. This is a useful way to check your understanding: vary one input and explain which path changes before looking at the answer.

Que. 3 Does printing Public event publish an Otahque event?

Flip to check your answerFold answer back

Answer. No. This example only displays text. It does not store an event, check Sam’s assignment, or make a page public. The real publication workflow must enforce those requirements on the server. A small Python branch is a language exercise, not a completed feature.

Trace a change instead of guessing

Assignment uses the values available when that line executes. It does not create a live formula that automatically follows later changes. Consider this separate arithmetic example, with fictional counts:

capacity = 12
active_count = 9
remaining = capacity - active_count
active_count = 10
print(remaining)

Trace the names after each step. A dash in Table 4.1 means that this example has not assigned that name yet; it is not a Python value.

Table 4.1 — Tracing the values in order
After step capacity active_count remaining
Set capacity 12 — —
Set active_count 12 9 —
Calculate remaining 12 9 3
Change active_count 12 10 3

The output is 3. To obtain 2 after the count changes, calculate remaining = capacity - active_count again after active_count = 10. The earlier result does not update itself. This explains a language rule; it is not a safe algorithm for allocating a real event’s final place. Shared records and overlapping requests need the later database and transaction lessons.

In practice: naming a decision clearly

Situation. A developer returns to an event-visibility condition several weeks after writing it.

Application. A name such as is_published helps them connect the Boolean value to the decision it controls. Checking both values exposes which branch supplies each result.

Consideration. A clear name is useful documentation, not enforcement. A visibility example still needs the application’s actual access rules before it can protect private data.

Try it yourself

Use the two examples above without running them. First, write the message produced by the branch when is_published is False, then when it is True. Second, in the arithmetic example, change only active_count = 10 to active_count = 12. Predict the printed result before and after adding a fresh calculation of remaining just before print. Explain every result in one sentence.

Que. 4 What should the predictions and explanations say?

Flip to check your answerFold answer back

Answer. False selects else and prints Private draft; True selects if and prints Public event. Changing active_count to 12 still leaves the earlier remaining value at 3, so the unchanged print displays 3. Recalculating just before printing subtracts 12 from 12 and displays 0. A new assignment changes a name’s value; an earlier calculation is not automatically repeated.

Decide what to practise next

If you can explain the branch and trace the changed values, continue to collections and loops. If you guessed, cover the answers and write the value of each name after every line. For a branch, underline the supplied condition and mark only the block it selects. Compare your trace with the worked results, then change one input and try again.

Common gaps are treating quoted text as a Boolean, using = when asking an equality question, ignoring indentation, or expecting a calculation to refresh itself. Practise the specific gap with another tiny example before adding Django syntax. You do not need to memorize every Python feature to proceed, but you should be able to explain these results in your own words.

Que. 5 Why predict a result before running the program?

Flip to check your answerFold answer back

Answer. The prediction makes your understanding visible. If the observed result later differs, you have a specific assumption to investigate. A successful run alone cannot tell you whether you understand the branch or whether the example satisfies the product requirements.

Further practice: for more examples of these ideas, the official Python 3.14 tutorial covers them in Numbers, Text, and if Statements. Try their short examples, then return here; you do not need the rest of the tutorial yet.

Collections and loops

Sam now has more than one event to describe. Giving every title a separate variable would make the same display task increasingly awkward. A collection groups values so that one piece of code can work through them. We will start with titles, add the details of one event, and then bring those ideas together.

Continue from the paper trace above. You need its assignment, Boolean, and indentation ideas, but no installed tools, working directory, files, or application checkpoint. Your output is an annotated event-list trace and predictions for changed inputs. Saving and running a file comes in How We Build It. All event details here are fictional practice data.

A list keeps items in order

A list is an ordered collection of items. Square brackets enclose the list, and commas separate its items. Here the items are strings:

titles = ["Python Evening", "Testing Clinic"]
print(titles[0])
print(len(titles))

Expected output:

Python Evening
2

An index identifies a position. Python starts list indexes at zero, so titles[0] selects the first item and titles[1] selects the second. The built-in len function gives the number of items. A length of 2 does not make 2 a valid positive index: these two positions are 0 and 1.

Que. 6 What happens if this example reads titles[2]?

Flip to check your answerFold answer back

Answer. Python raises IndexError because that position does not exist. It does not return an empty string. Count the items and check the index before changing the example; do not add a made-up event just to hide the mistake. Reading error messages comes at the end of this part.

A dictionary gives each detail a key

One event has several related details. A dictionary associates keys with values. In this example, the keys are the strings "title" and "is_published". Curly braces enclose the dictionary; a colon separates each key from its value, and commas separate the pairs.

event = {
    "title": "Python Evening",
    "is_published": True,
}
print(event["title"])
print(event["is_published"])

Expected output is Python Evening, then True, on separate lines. The trailing comma after the final pair is allowed. Splitting the dictionary across lines makes its details easier to read; it is still one assignment.

The brackets after event perform a lookup. Unlike a list index, "title" names a key rather than a position. The key "is_published" is text; its associated value True is a Boolean. A key and its value do different jobs, even when they appear together.

Que. 7 Are event["title"] and event["Title"] interchangeable?

Flip to check your answerFold answer back

Answer. No. These are different string keys. This dictionary contains "title", so looking up "Title" raises KeyError. Check the spelling and capitalization against the supplied data. Also, event[0] would look for the key 0; it would not mean “the first detail”.

Repeat a task with a for loop

A loop repeats a block of code. A for loop takes each item from a collection in turn. Each pass through the block is an iteration. This separate example uses the two titles again:

titles = ["Python Evening", "Testing Clinic"]
for title in titles:
    print(title)
print("Finished")

Read the for line as “for each item in titles, bind title to that item and run the indented block”. The singular name title is our choice, not special Python syntax. On the first pass it refers to "Python Evening"; on the second it refers to "Testing Clinic".

Expected output:

Python Evening
Testing Clinic
Finished

The final print lines up with for, so it runs once after the loop. Moving it four spaces to the right would put it inside the loop and print Finished after each title. Indentation determines which work repeats. This loop reads the list without changing it.

Que. 8 What changes if titles is an empty list, written []?

Flip to check your answerFold answer back

Answer. There are no items, so the loop body runs zero times. The final print still runs and displays Finished. An empty collection is a valid input to a for loop; the loop does not invent a first item.

Combine a list, dictionaries, and a decision

We can put dictionaries inside a list. The outer list groups events; each dictionary groups the details of one event. This is a small in-memory representation for learning, not a database model or saved application data. Read this complete example from the assignment onward:

events = [
    {"title": "Python Evening", "is_published": True},
    {"title": "Testing Clinic", "is_published": False},
]

for event in events:
    if event["is_published"]:
        print(event["title"])
print("Review complete")

The two kinds of lookup are separated in Figure 4.2. events[0] selects a dictionary by its position in the list. Adding ["title"] selects the title from that dictionary. In the loop, event already refers to the current dictionary, so we use event["title"] directly.

A box labelled events, a list of two dictionaries. Index 0 holds "title": "Python Evening" and "is_published": True; index 1 holds "Testing Clinic" and False. An arrow labelled events[0]["title"] leads from the first dictionary to the result "Python Evening". A note explains that [0] picks by position and ["title"] then picks by key.
Figure 4.2 — Select an event by position, then a detail by key.

The if line sits four spaces inside for. Its print sits eight spaces in, inside both blocks. There is no else: when the supplied Boolean is False, the body of if is skipped and the loop continues with its next item, if any. The last print is outside both blocks.

Table 4.2 — Following each event through the loop
Pass Current title Condition Title printed
1 Python Evening True Python Evening
2 Testing Clinic False —

A dash in the last column means that no title is printed on that pass. Expected output:

Python Evening
Review complete

This trace selects a display message from supplied data. It neither publishes an event nor proves that a visitor may access it. Later server-side code must enforce the real visibility rules. We also keep the collection unchanged during iteration; adding or removing its items while traversing it needs separate care.

Que. 9 Does for event in events loop over dictionary keys?

Flip to check your answerFold answer back

Answer. No. Here events is a list, so each item supplied to the loop is a whole dictionary. A loop directly over a dictionary would yield its keys. Check the collection after in before deciding what the loop variable represents.

In practice: checking a collection with no results

Situation. A future event list has no published events to show, although the code was first tried with several examples.

Application. Use the empty-list case to reason about what a loop does when it has no items. Decide what the surrounding program should do after that loop.

Consideration. Do not assume there is always a first item to read. The chapter’s in-memory collection is practice data, not a saved event database.

Try it yourself

Trace the complete events example three times on paper. First, change the second is_published value to True. Second, make both values False. Third, replace the entire list assignment with events = []. For each case, write the exact output and the number of loop-body executions. Keep the final print outside the loop.

Que. 10 What should the three traces show?

Flip to check your answerFold answer back

Answer. With both values True, the output is Python Evening, Testing Clinic, and Review complete on three lines; the loop body runs twice. With both values False, only Review complete appears, but the loop body still runs twice and checks both conditions. With events = [], only Review complete appears and the loop body runs zero times. No printed titles can therefore mean either an empty list or a non-empty list with no matching events.

Check your readiness

You are ready for the next section when you can distinguish a list position from a dictionary key and explain which lines run for every item. If your trace differs, draw the list positions, write the current dictionary beside each pass, and mark the indentation levels. Keep your first prediction so that you can identify the assumption you corrected. Revisit the empty case as well as the two-event case.

Further practice: for more examples of these ideas, the official Python 3.14 tutorial covers them in More on Lists, Dictionaries, and for Statements. Try their short examples, then return here; you do not need the rest of the tutorial yet.

Functions and imports

Sam wants the same event-label rule in more than one place. Copying a branch each time creates several places to correct when the rule changes. A function gives that small task a name and lets another part of the program ask for its result.

Continue tracing on paper. No installation or application checkpoint is needed yet. This section produces a call trace and a two-file sketch; How We Build It supplies the saving and running steps. The example chooses text from supplied practice values, not access to a real event.

Define a task, then call it

def event_label(title, is_published):
    if is_published:
        return title
    return "Private draft"

The keyword def begins a function definition. event_label is the function name. The names title and is_published inside its parentheses are parameters: local names for values supplied when the function is called. The colon and indented body have the same structural role you met with if and for.

Executing this definition makes the function available; it does not yet run the branch or print anything. A call uses parentheses after the function name. The supplied values are arguments. Read this after the definition above:

message = event_label("Python Evening", True)
print(message)

The first argument becomes the local title and the second becomes the local is_published. The True branch reaches return title. return ends this call and supplies its result to the caller, the code that made the call. The assignment binds message to "Python Evening"; only the following print displays it. With False, execution skips that branch and reaches return "Private draft".

The caller supplies Python Evening and True to event_label. Its selected return sends Python Evening back to message. A separate print call displays that message.
Figure 4.3 — A function returns a value to its caller.

Que. 11 What happens to the second return when is_published is True?

Flip to check your answerFold answer back

Answer. It is not reached during that call. The first return ends the function call. A later call starts a new execution of the body with its own supplied arguments.

Returning and printing do different jobs

A returned value can be stored, compared, or passed to another operation. Printing sends a textual representation to the output destination. It does not give the printed text back as the result of your function. Compare this deliberately different function:

def show_title(title):
    print(title)

result = show_title("Python Evening")
print(result)

Expected output:

Python Evening
None

show_title prints the first line. It then reaches the end without a return value, so its call returns None, Python’s value for the absence of a result here. The outer print displays that value. None is neither the empty string nor the string "None". Use event_label when a caller needs the text as data; printing can remain the caller’s choice.

Que. 12 Would assigning a call to a variable prevent its internal print?

Flip to check your answerFold answer back

Answer. No. result = show_title(...) still executes the function body, including print. Assignment stores the returned value; it does not cancel other work performed during the call.

Keep track of local names

Scope is the region in which a name can be looked up. A function’s parameters and ordinary assignments inside it are local to that call. The following separate example has two names spelled title:

title = "Python Evening"

def replace_title(title):
    title = "Private draft"
    return title

print(replace_title(title))
print(title)

The output is Private draft, then Python Evening. Reassigning the local parameter does not reassign the caller’s title. This does not mean that Python copies every argument: a function can change a supplied list or dictionary if it performs a modifying operation on that object. Our label function only reads its arguments.

Que. 13 Can the caller read a function’s local variable by using its name after the call?

Flip to check your answerFold answer back

Answer. Not merely because the function created it. A local name is not automatically added to the caller’s scope. Return the value that the caller needs and assign that result there. If no binding for a name can be found, Python raises NameError.

Put reusable definitions in a module

For our purposes, a module is a Python file containing definitions and statements. Sketch two files in the same directory. event_text.py contains only the event_label definition shown above. preview.py contains the following complete runner:

from event_text import event_label

print(event_label("Python Evening", True))
print(event_label("Testing Clinic", False))

from event_text import event_label makes that function name available in preview.py. The module name omits the .py ending. These two calls print Python Evening and Private draft, on separate lines. A second spelling is import event_text followed by event_text.event_label(...); the dot accesses the function through the module name. Do not mix the two spellings without understanding which names the import introduced.

An import can execute a module’s top-level statements when the module is first loaded in that interpreter. Our reusable module contains only a definition, so importing it does not print an event. Keep demonstration calls in preview.py. Imports make available code usable; they do not install a missing package.

Under the Hood: how import finds a module

from event_text import event_label asks Python to find a module named event_text. Python first checks sys.modules, the modules already loaded in this run. Otherwise it searches the directories listed in sys.path in order; the first entry is normally the directory of the script you ran, which is why preview.py finds event_text.py beside it. The first match wins, so a local file named after a library module, such as json.py, hides the real one. A module is executed once per run, when it is first imported, and the loaded module is reused after that.

That search order has a practical side when two files need the same code.

In practice: sharing a small piece of behaviour

Situation. Two parts of a project need the same event-label wording, and separately copied versions begin to differ.

Application. Put the shared operation in a function and import it where needed. Returning the label lets each caller decide how to use the result.

Consideration. Only share behaviour that really has the same meaning. Importing a module should not unexpectedly run its demonstration program.

Try it yourself

In the two-file sketch, change only the first preview.py call’s argument True to False. Predict both output lines. Then explain why putting print("Loaded") at the top level of event_text.py would add a line before those results in a fresh run. Leave that extra print out of the reusable file.

Que. 14 What should the changed preview show, and what would the extra print do?

Flip to check your answerFold answer back

Answer. Both event_label calls would return Private draft, so the runner would print that text twice. A top-level print("Loaded") in event_text.py would execute when the import first loads that module and print Loaded before the two calls. The definition itself would still not run its body until called.

Further practice: for more examples of these ideas, the official Python 3.14 tutorial covers them in Defining Functions and Modules. Try their short examples, then return here; you do not need the rest of the tutorial yet.

Classes and reading errors

Soni compares two event cards. Each has its own title, but both can produce a label in the same way. A class can describe that shared behaviour while each instance holds its own data. We need enough of this vocabulary to read later Django examples, without designing a database model yet.

Start from the functions and calls above. This section remains a paper exercise: explain two instances and diagnose a short failure. The named files are sketches that you can save and run in How We Build It. No application or database exists at this checkpoint.

Read a class one part at a time

Sketch event_card.py with this complete definition:

class EventCard:
    def __init__(self, title):
        self.title = title

    def label(self):
        return "Event: " + self.title

class EventCard defines a new kind of object. An instance is one object created from that class. Calling EventCard("Python Evening") makes an instance and initializes it using __init__. The name __init__ has two underscores at each end; it is a special initialization method recognized by Python.

A method is a function associated with a class. self is the conventional name for the instance supplied to an instance method. In self.title = title, the right-hand title is the argument’s local name; self.title is an attribute, a named value attached to this instance. The dot selects that attribute. label reads it and uses + to join two strings.

Sketch class_demo.py beside event_card.py:

from event_card import EventCard

first = EventCard("Python Evening")
second = EventCard("Testing Clinic")
first.title = "Python Afternoon"
print(first.label())
print(second.label())

Expected output:

Event: Python Afternoon
Event: Testing Clinic

first and second refer to separate instances. Changing first.title in this example changes only first’s title attribute. When first.label() is called, Python supplies first as self; we do not pass it again. The method returns the assembled string, and the surrounding print displays it.

The EventCard class lists its __init__(self, title) and label(self) methods. Arrows labelled instance lead to two separate objects: first, whose title is now "Python Afternoon", and second, whose title is "Testing Clinic". A note says changing first.title leaves second.title unchanged.
Figure 4.4 — Two instances use one class definition.

Que. 15 Why does label(self) have a parameter when first.label() has no argument inside the parentheses?

Flip to check your answerFold answer back

Answer. Calling this instance method through first supplies that instance automatically as self. Other parameters, if the method defined any, would need their own arguments. self is a convention for this role, not the name of a global event.

Recognize inheritance without designing around it

A class can build on another class. This is inheritance. After importing EventCard, the following small example defines a subclass named PreviewCard; EventCard is its base class. pass means “no statement to perform here” and provides the required body:

from event_card import EventCard

class PreviewCard(EventCard):
    pass

card = PreviewCard("Python Evening")
print(card.label())

The output is Event: Python Evening. PreviewCard has not replaced the inherited initialization or label method, so those behaviours are available through it. The name PreviewCard does not enforce privacy. Later Django classes will use inheritance for concrete purposes; this example teaches how to recognize the parentheses after a class name.

Separate three kinds of mistake

An error message is evidence about an execution, not a judgement about your ability. Begin by deciding whether Python could read the program, whether an operation failed while it ran, or whether it ran but gave an incorrect result.

Table 4.3 — Three kinds of mistake
Kind Example First check
Syntax A missing colon after def Read the reported line and the line before it.
Runtime Looking up a missing dictionary key Read the exception type and the failing operation.
Logic Returning a draft label for a published event Compare actual output with a prediction and the intended rule.

SyntaxError means Python could not parse the code. IndentationError is a syntax-related error. An exception raised during execution may be KeyError, NameError, TypeError, or another specific type. A logic mistake may raise no exception at all, which is why our changed-input predictions matter.

Read a traceback from the failure back to its caller

This deliberately failing sketch is error_demo.py. Count its blank lines too when locating line numbers:

def read_title(event):
    return event["title"]


sample = {"name": "Python Evening"}
print(read_title(sample))

The relevant traceback is shown below with the directory part of each filename and any caret markers omitted. Those display details can vary. The exception type and the two call locations are the evidence to follow:

Traceback (most recent call last):
  File "error_demo.py", line 6, in <module>
    print(read_title(sample))
  File "error_demo.py", line 2, in read_title
    return event["title"]
KeyError: 'title'

Read the final line first: the key "title" was not found. The frame immediately above it locates the lookup in read_title. A frame identifies one step in the chain of calls; the earlier frame shows which call supplied sample. Inspect sample: it has the key "name", while this function expects "title". Python cannot infer that those words were meant to refer to the same detail.

For this exercise, the agreed input shape uses "title". Correct the sample key in a separate copy of the file, keeping the original as evidence. Running the corrected copy should print Python Evening. Changing unrelated code or catching every exception and printing “success” would obscure the cause.

Que. 16 Does the final traceback frame always contain the original cause?

Flip to check your answerFold answer back

Answer. It shows where this exception was raised, which is a useful starting point. Here the failed lookup is in the function, but the mismatched input was created by its caller. Follow the values through the call chain before deciding what to change.

In practice: handing over a reproducible failure

Situation. A small Python program fails for a particular input, and another developer needs to investigate.

Application. Keep the exception type, relevant traceback lines, and a minimal example of the input. Trace the value from its caller to the failing operation before changing code.

Consideration. Remove private data before sharing the example. The line where an exception appears may be downstream from the mistake that supplied the value.

Try it yourself

Explain what each of these changes would do, without executing them yet: change first.title in class_demo.py to first.name; call event_label("Python Evening") without its second argument; and repair the sample key in error_demo.py. Predict the symptom or output, and identify the smallest useful check.

Que. 17 What diagnoses fit the three changes?

Flip to check your answerFold answer back

Answer. Assigning first.name creates a different attribute on this simple class; label still reads the unchanged first.title, so the first output remains Event: Python Evening. This is a logic mistake, not necessarily an exception. Calling event_label with only one argument raises TypeError because is_published is required. Correcting the sample key to "title" lets read_title return Python Evening. Check the name the method reads, the function’s parameters, and the dictionary’s keys respectively.

Further practice: for more examples of these ideas, the official Python 3.14 tutorial covers them in A First Look at Classes, Inheritance, Syntax Errors, and Exceptions. Try their short examples, then return here; you do not need the rest of the tutorial yet.

PAGE 002

How We Build It

Starting point: the paper examples in What You Need to Know; no existing application checkpoint. You need a plain-text editor, a terminal, and internet access for the initial tool downloads. These steps install uv 0.13.5, select CPython 3.14.9, create a folder named otahque-python-practice with a few small Python files and a .venv/ environment, and end with a readiness program that prints Readiness checks passed. No Django package is needed yet.

The Custom Way: whatever Python the shell finds

The most direct way to run a file is to type the name of a Python program and the file. Read this listing; you do not need to run it:

python --version
python preview.py

It sometimes works, and that is the problem. python is not a fixed program: the shell searches the directories on its PATH and runs the first match. On one computer that is Python 3.14, on another an older 3.x, on a third nothing at all; on Windows, typing python without an installation can open the Microsoft Store instead. Installed packages then land in whichever Python ran, and two projects that need different versions of a package collide. Nothing in the command records which interpreter you meant. The two steps below replace that guesswork with uv, a pinned Python, and an environment we can name in every command.

Step 1: Run saved files from an editor and a terminal

Sai wants to check the predictions rather than trust them. She needs to know which file she saved, where her terminal is working, and which Python will run it. Those are three separate questions; a useful setup makes each answer visible.

This step installs uv 0.13.5 and uses it to select CPython 3.14.9. CPython is the standard implementation of Python. You will create two runnable files in a new folder named otahque-python-practice and compare their output with your predictions from What You Need to Know.

Identify the three tools

An editor lets you write and save plain text. A terminal is the window in which you interact with a command-line program. A shell interprets commands typed there: use PowerShell on Windows, or the usual shell in macOS Terminal or Linux/WSL. WSL is Windows Subsystem for Linux; its terminal follows the Linux instructions, not the PowerShell ones. The Python interpreter is the program that executes Python source code.

On Windows, Windows Terminal can open different shells in separate tabs. Choose a PowerShell tab for the Windows commands in this book. Command Prompt (cmd.exe) is another shell with different command syntax. Bash is a shell commonly used on Linux; a Bash tab inside WSL follows the Linux/WSL instructions. Check the tab’s shell before copying a command; the terminal window alone does not tell you which syntax to use.

An editor saves preview.py to the practice directory. A separate shell command starts the selected Python interpreter with that filename. Python reads the file and sends its printed output back to the terminal.
Figure 4.5 — Save a file, then ask Python to run it.

Use an editor you already know that saves plain text and preserves indentation. Configure it to insert four spaces for each indentation level. A word processor is not suitable for .py files. On Windows, show filename extensions and check that the saved name is preview.py, not preview.py.txt. Keep ordinary straight quotation marks in source code.

Install uv and select the pinned Python

New Tool: uv

What problem exists? Each project needs a known Python version and its own installed packages, and the command that runs it should say which.

What did people do before? They installed Python versions by hand, created environments with the built-in venv module, and installed packages with pip, using separate tools and commands that differ between platforms.

What is uv? A tool from Astral that installs Python versions, creates virtual environments, and manages packages from one consistent command line.

Why uv? One tool and one command form on Windows, macOS, and Linux, with the exact version named in every command. The standard-library venv module remains valid; this book uses uv to keep Python selection and environment management in one workflow.

Now let’s install it.

A virtual environment is still the underlying isolation mechanism; we will inspect one in Step 2.

This book pins uv 0.13.5, the current stable release when this chapter was written (October 2026), and CPython 3.14.9. Python 3.14 is compatible with the planned Django 6.1 series. Pinning means naming the exact version used for the examples. Recheck versions at a future setup checkpoint rather than silently changing them halfway through the exercises.

If uv is not installed, use Astral’s versioned installer below. These commands download and execute its installation script, so use the official address as shown. No existing Python installation is required. On a managed computer, use your administrator’s approved installation route. Run commands at the shell prompt, not at Python’s >>> prompt; do not type a prompt symbol.

Windows PowerShell (the backtick continues the command on the next line):

$uvInstaller = 'https://astral.sh/uv/0.13.5/install.ps1'
powershell -ExecutionPolicy Bypass -Command `
    "Invoke-RestMethod '$uvInstaller' | Invoke-Expression"

The execution-policy option applies to that child PowerShell process. It does not change the machine’s permanent policy. Follow the installer’s completion message and open a new PowerShell window so it can find uv.

macOS Terminal or Linux/WSL Bash:

curl -LsSf https://astral.sh/uv/0.13.5/install.sh | sh

Open a new terminal after installation. If curl is unavailable, follow Astral’s installation guide for an alternative supported method. Windows Subsystem for Linux uses the Linux installation inside WSL, separately from Windows.

All platforms: check uv before continuing. If you already have it, start here rather than rerunning the installer.

uv --version

The version must begin with uv 0.13.5, the version used throughout this book; build information may follow. If uv is not found, reopen the terminal and follow the installer’s PATH guidance. PATH is the list of directories your shell searches for commands. If another version appears, inspect Get-Command uv in PowerShell or command -v uv on macOS/Linux, then select the intended installation. Do not overwrite a shared installation merely to match this exercise.

All platforms: install the selected Python and check it:

uv python install 3.14.9
uv run --no-project --python 3.14.9 python --version

The install command downloads Python if needed. uv-managed CPython builds come from Astral’s python-build-standalone project; they are not the python.org graphical installer. The second command asks uv to run Python with the requested version. --no-project keeps these exercises independent of any enclosing uv project. uv may warn that no project was found; that warning is expected here and does not mean the Python command failed.

Expected Python output:

Python 3.14.9

If the download fails, preserve the error and check connectivity, available disk space, and permission to write to the installation directory before retrying. Do not replace the operating-system Python. If the version differs, stop and inspect the command and selected installation before creating the environment.

Official guides: https://docs.astral.sh/uv/getting-started/installation/ and https://docs.astral.sh/uv/guides/install-python/. These steps have been tested on Windows. The macOS, Linux, and WSL commands follow Astral’s documentation but have not yet been tested for this book; if one behaves differently, follow the official guides and please report the difference.

Choose a directory you can identify

A directory is a folder. The current working directory is the folder the shell uses to resolve relative paths such as preview.py. Choose an existing parent folder where you keep learning work, open your terminal there, and inspect it before creating anything:

Windows PowerShell:

Get-Location
Get-ChildItem

macOS Terminal or Linux/WSL Bash:

pwd
ls

The first command prints your current path; the second lists its entries. Your path will differ from another reader’s. Create the practice directory only if that name is not already in use:

Windows PowerShell:

New-Item -ItemType Directory otahque-python-practice
Set-Location otahque-python-practice
Get-Location

macOS Terminal or Linux/WSL Bash:

mkdir otahque-python-practice
cd otahque-python-practice
pwd

The final path must end in otahque-python-practice. If that folder already exists, inspect it; use it only if it is your intended practice folder. Otherwise choose a new name, such as otahque-python-practice-2, in both commands. Do not delete or overwrite an existing folder to follow the example. A path containing spaces needs quotation marks when used as a command argument.

Save the reusable module and runner

Open that same directory in your editor. Create event_text.py and save this complete content; it is the function from “Functions and imports”:

def event_label(title, is_published):
    if is_published:
        return title
    return "Private draft"

Create preview.py beside it, with this complete content:

from event_text import event_label

print(event_label("Python Evening", True))
print(event_label("Testing Clinic", False))

Save both files before running. In the shell, still inside the practice directory, check the filenames and execute the runner:

Windows PowerShell:

Get-ChildItem
uv run --no-project --python 3.14.9 preview.py

macOS Terminal or Linux/WSL Bash:

ls
uv run --no-project --python 3.14.9 preview.py

Expected output:

Python Evening
Private draft

The command names the file to execute. Python can find event_text.py beside the runner; the import makes its function available. After the program ends, the shell prompt returns. Running the file again starts a fresh interpreter execution. You may also notice a __pycache__ directory containing cached imported code; it is not the source file you edit.

Recognize the interactive prompt

Running uv run --no-project --python 3.14.9 python without a script filename opens interactive Python and shows >>> after a version banner. At that prompt, enter Python statements such as print("Hello"). A directory-changing shell command does not belong there. To return to the shell, type exit() and press Enter. The >>> and continuation ... markers are prompts, not text to copy into a .py file.

Que. 18 Why can a program still print the old title after you edit it?

Flip to check your answerFold answer back

Answer. The editor’s unsaved buffer and the file on disk can differ, or the terminal may be running another copy. Save the intended file, inspect the current directory and filenames, and rerun the exact command. A shell run does not automatically use whichever editor tab you last clicked.

Recover from a failed first run

Table 4.4 — First-run symptoms and non-destructive checks
Symptom Check Recovery
Cannot open preview.py Current path and actual filename Navigate to the correct folder; check for a hidden .txt ending.
ModuleNotFoundError: event_text Both files are saved together Correct the name/location; do not install a package with that name.
SyntaxError or IndentationError Reported line, previous line, quotes, spaces Keep a copy; correct one difference against the listing and rerun.
Output differs Arguments and saved contents Trace True/False again; compare the saved file with the prediction.

Keep the filenames shown here. Local filenames can hide modules a program imports: for example, a file named json.py could hide Python’s standard-library json module. Keep recovery focused on the file or interpreter that the error identifies.

In practice: comparing two developers’ runs

Situation. The same saved example appears to work for one developer and fail for another.

Application. Compare the working directory, saved file, uv version, and selected Python version before editing the program. These observations make the difference easier to reproduce.

Consideration. Matching filenames alone does not establish that both people ran the same contents or interpreter. Keep the exact command with the report.

Try it yourself

Keep preview.py unchanged. Save a copy as preview_changed.py in the same directory. In the copy, change the second call’s False to True. Predict the output, then run the new filename:

Windows PowerShell:

uv run --no-project --python 3.14.9 preview_changed.py

macOS Terminal or Linux/WSL Bash:

uv run --no-project --python 3.14.9 preview_changed.py

Que. 19 What output verifies the change?

Flip to check your answerFold answer back

Answer. The two lines should be Python Evening and Testing Clinic. The second call now returns its supplied title. Running preview.py should still show Python Evening and Private draft, which confirms that you preserved the original and ran the intended copy.

Step 2: Create a virtual environment and run the readiness check

New Concept: virtual environment

What problem exists? Two projects can need different versions of the same package, and installing one would break the other.

What did people do before? Installing all packages into one shared Python is a simpler starting arrangement, but one project’s dependency changes can affect another.

What is a virtual environment? A Python environment with its own package installation area, built on a base Python. Packages installed into it do not change the base installation or other environments.

Why use one? Each project gets its own packages, and its interpreter path tells you exactly which environment ran.

Now let’s create one beside the practice files.

Sai can now run the two files. This step gives them an environment of their own, with an interpreter path we can check.

Starting point: completed Step 1, with event_text.py and preview.py in otahque-python-practice, uv 0.13.5 available, and CPython 3.14.9 verified. Keep the shell in that directory. This section creates .venv beside your source files, records the Python pin, adds an identity-check file, and finishes with a small readiness program. No third-party packages or Django are required.

Create the environment with the selected Python

Use uv to record the Python version and create the environment. First inspect the directory: if .python-version already exists, read it before changing it; if .venv exists, use the recovery instructions below. For this new practice directory, run these commands in PowerShell or a macOS/Linux/WSL shell:

uv python pin 3.14.9
uv venv --python 3.14.9

The first command writes 3.14.9 into .python-version. uv can read that file when selecting Python; it is not a package list or a dependency lock. The second command creates .venv using the requested Python. Expect a creation message naming .venv and possibly an activation hint. Windows stores its Python executable under Scripts; macOS/Linux uses bin. Your source files stay beside the environment.

The practice directory contains editable Python source files and a separate .venv directory. The environment holds its interpreter entry point and installed packages, and depends on the selected base Python 3.14.9. A run command selects that environment interpreter to read the source files.
Figure 4.6 — Source files stay beside the isolated environment.

If .venv already exists, inspect it with the identity checks below instead of recreating it over unknown contents. If it is wrong or incomplete, preserve it and run uv venv --python 3.14.9 .venv-check in a fresh directory name; substitute .venv-check wherever later commands select .venv. For creation failures, read the error, check the selected Python and directory permissions, correct the cause, and retry into a new environment directory. No pip bootstrap is needed.

Use the environment without depending on activation

Run preview.py through the selected environment. This command is the same in PowerShell and macOS/Linux/WSL shells:

uv run --no-project --python .venv preview.py

The output must still be Python Evening, then Private draft. Here --python .venv selects the environment directory explicitly. Activation is an optional shell convenience that changes command lookup; it does not create the environment. These uv commands do not need activation. The expected no-project warning described in Step 1 may also appear.

Que. 20 Does an environment choose a different Python version merely because its directory is named .venv?

Flip to check your answerFold answer back

Answer. No. uv venv --python 3.14.9 selects the base Python used to create it. The name .venv is a convention. Choosing the intended base interpreter and inspecting the resulting environment are separate from naming its folder.

Verify the interpreter, not just the prompt

Create check_environment.py beside preview.py with the following complete content:

import sys

print(sys.version.split()[0])
print(sys.executable)
print(sys.prefix)
print(sys.base_prefix)
print(sys.prefix != sys.base_prefix)

The standard library is the collection of modules included with Python. sys is one of those modules. sys.version contains interpreter version information; split() separates its whitespace-delimited parts and [0] selects the first, the version number. sys.executable identifies the running interpreter. sys.prefix identifies its environment prefix, while sys.base_prefix identifies the base installation. The != comparison asks whether the two prefixes differ.

All platforms:

uv run --no-project --python .venv check_environment.py

Read the five output lines in order. The first must be 3.14.9. The executable path should identify .venv/Scripts/python.exe on Windows or .venv/bin/python on macOS/Linux, with your machine’s path separators. The next line identifies .venv; the following line identifies the base Python installation. The final line must be True. Paths differ between computers, so compare their roles rather than copying a sample absolute path.

A False final line means the interpreter reports that it is outside a virtual environment. Check the exact executable used by the command, not just the prompt’s appearance. A different version means the environment was created with another base interpreter. Preserve the source files and create a new environment using the verified 3.14.9 installation.

Keep the package tool attached to the interpreter

uv has a pip-compatible interface for inspecting and managing packages. It does not invoke a separately installed pip program. Inspect this environment without installing anything:

All platforms:

uv pip list --python .venv

In this freshly created environment, the command succeeds with no package rows; output may be empty. Python’s standard-library modules are not third-party package rows. uv venv does not install pip by default, and uv pip does not need it in the environment. A missing pip module is therefore not an error to repair here. The --python .venv option identifies exactly which environment to inspect. Do not add packages for this exercise.

A virtual environment isolates package availability by default; it is not a security boundary against programs you run. It also depends on its base Python and contains machine-specific paths. Keep your source files as the durable work; recreate an environment on another machine rather than copying its directory. Chapter 8 will develop dependency records and reproducible project setup.

Official references: https://docs.astral.sh/uv/pip/environments/ and https://docs.python.org/3.14/library/sys.html. Once the selected Python is installed, these local, dependency-free runs and package inspections need no download. Chapter 8 will introduce uv project metadata, dependencies, and locking; we do not run uv init or create a lockfile here.

Que. 21 Can a successful import or a prefix comparison prove that the future Django application is correct?

Flip to check your answerFold answer back

Answer. No. These checks establish which interpreter and package environment you are using. Application behaviour needs its own examples and tests. The files here still operate only on fictional in-memory values.

Bring the language pieces together

Save event_card.py using the complete class definition from “Classes and reading errors”. For convenience, its exact content is repeated here; keep it beside event_text.py, not inside .venv:

class EventCard:
    def __init__(self, title):
        self.title = title

    def label(self):
        return "Event: " + self.title

Create readiness.py with this complete content:

from event_card import EventCard
from event_text import event_label


def count_published(events):
    count = 0
    for event in events:
        if event["is_published"]:
            count = count + 1
    return count


events = [
    {"title": "Python Evening", "is_published": True},
    {"title": "Testing Clinic", "is_published": False},
]
assert count_published(events) == 1
assert count_published([]) == 0
assert event_label("Testing Clinic", False) == "Private draft"
assert event_label("Python Evening", True) == "Python Evening"
card = EventCard("Python Evening")
assert card.label() == "Event: Python Evening"
print("Readiness checks passed")

count starts at zero for each call. Each matching event adds one; the return is outside the loop, so all items are considered before the count is returned. An empty list skips the body and returns zero. The imports reuse the label function and the class, while card is one instance of that class.

assert evaluates a condition and raises AssertionError if it is false in these normal runs. The checks cover a mixed list, an empty list, both label branches, and an instance method. Only after they pass does the final message print. These are small learning checks; do not use assertions for application authorization or input validation, because optimized Python execution can disable them. Run the commands as written, without an optimization option.

All platforms:

uv run --no-project --python .venv readiness.py

Expected output:

Readiness checks passed

If you see AssertionError, identify the failed comparison and predict the actual value before editing. If an import fails, check that readiness.py, event_text.py, and event_card.py are saved together. Do not remove the failing assertion to obtain the success message. Keep a copy before changing a working example.

In practice: working on two Python projects

Situation. A developer maintains an older project while learning with a separate practice project.

Application. Give each project its own virtual environment and use uv to select the intended one. This separates their installed packages while keeping source files outside the environment.

Consideration. An environment is not a portable dependency record or a security boundary. Chapter 8 will develop dependency records and reproducible project setup.

Try it yourself

Save readiness.py as readiness_changed.py. Change the second event’s False to True and predict what happens before running it. Then adjust the expected count to match this changed input, leaving the empty-list and label checks intact. Finally, explain what goes wrong if return count is indented inside the for loop.

Que. 22 What should the changed run and diagnosis show?

Flip to check your answerFold answer back

Answer. The first run raises AssertionError at the comparison with 1, because both events now match and count_published returns 2. Change that expected count to 2; the success message should return and the other checks still pass. Moving return count inside the loop would exit after the first item. With no items, that misplaced return would never run, so the function would return None instead of zero. The empty-list check helps expose that mistake.

To run the changed copy, use the same environment interpreter and substitute readiness_changed.py for readiness.py in the preceding command. You now have evidence from a prediction, an observed failure, and a reasoned correction. The unchanged readiness.py remains your reference.

PAGE 003

Verify Your Work

Automated tests begin in Chapter 9. For now, run the checks in Table 4.5 from your otahque-python-practice folder. All of them should pass before Chapter 5; record your actual results in readiness-notes.txt.

Table 4.5 — Verification checklist for Chapter 4
Check Command or action Expected result
uv installed uv --version Begins with uv 0.13.5
Python selected uv run --no-project --python 3.14.9 python --version Python 3.14.9
Files saved together Get-ChildItem or ls event_text.py and preview.py in the practice folder
Program runs uv run --no-project --python 3.14.9 preview.py Python Evening, then Private draft
Environment identity uv run --no-project --python .venv check_environment.py 3.14.9, a .venv interpreter path, two prefixes, True
Environment packages uv pip list --python .venv Succeeds with no package rows
Readiness program uv run --no-project --python .venv readiness.py Readiness checks passed

If a check fails, use Table 4.4 for first-run problems, and the environment checks in Step 2 for the rest. Do not remove a failing assertion to obtain the success message.

PAGE 004

Checkpoint: Quiz and Challenge

Quiz

Que. 23 What does titles[0] select, and why is titles[1] not the first item?

Flip to check your answerFold answer back

Answer. The first item: Python counts list positions from zero, so titles[1] is the second item.

Que. 24 What is the difference between a parameter and an argument?

Flip to check your answerFold answer back

Answer. A parameter is the local name in the function definition, such as title; an argument is the value supplied by a call, such as "Python Evening".

Que. 25 In first.label(), what does self refer to inside label?

Flip to check your answerFold answer back

Answer. The instance first. Python supplies it automatically as the first argument of an instance method.

Que. 26 Which line of a traceback should you read first, and why?

Flip to check your answerFold answer back

Answer. The last line, which names the exception and its message. Then read the frames above it to see which calls led there.

Que. 27 check_environment.py prints True on its last line. What does that tell you, and what does it not?

Flip to check your answerFold answer back

Answer. That the running interpreter is inside a virtual environment, because its prefix differs from the base prefix. It does not show which environment, which is why the executable path matters, and it says nothing about whether any program is correct.

Mini-Challenge

Add a function to readiness_changed.py named published_titles(events) that returns a list of the published titles, in order. Use a for loop, an if, and the list method append, which adds an item to the end of a list. Add two assertions: one for the two-event list and one for the empty list. Run the file with the same environment.

Que. 28 What would a working answer look like?

Flip to check your answerFold answer back

Answer. For example:

def published_titles(events):
    titles = []
    for event in events:
        if event["is_published"]:
            titles.append(event["title"])
    return titles


assert published_titles(events) == ["Python Evening"]
assert published_titles([]) == []

The return sits outside the loop, so every event is considered. The empty list returns an empty list rather than None. With the original two events, the run still ends with Readiness checks passed.

What We Learned

  • Assignment binds a name to a value, and comparison asks a question; an if runs only the branch its condition selects.
  • Lists select by position from zero, dictionaries by key, and a for loop runs its body once per item, including zero times for an empty list.
  • A function returns a value to its caller; printing displays text but returns None.
  • A class defines shared behaviour, and each instance keeps its own attributes; self is the instance a method was called on.
  • Read a traceback from its last line, then follow the values back through the calls.
  • uv pins Python 3.14.9 and creates .venv; naming --python .venv in commands makes the interpreter you ran visible and checkable.

Key terms

Use Table 4.6 to check the vocabulary from this chapter before Chapter 5.

Table 4.6 — Key terms from Chapter 4
Term Meaning in this chapter
Value and type A piece of data and the kind of value it is, such as string, integer, or Boolean.
Assignment and comparison Binding a name to a value versus asking a question about values.
List and index An ordered collection and a position used to select an item.
Dictionary and key A collection of key–value pairs and a key used to look up a value.
Iteration One pass through a loop’s body.
Function; parameter; argument A named task; a local input name; a value supplied by a call.
Return and scope Supplying a call’s result; the region in which a name can be looked up.
Module and import A unit of Python code, here a file; making its definitions available.
Class and instance A definition of object behaviour and one object created from it.
Attribute and method A named value on an object and a function associated with a class.
Inheritance Defining a class that builds on a base class.
Exception and traceback An execution failure and the reported chain of calls leading to it.
Shell and interpreter The command processor and the program executing Python code.
Working directory The folder used to resolve relative paths.
Virtual environment A Python environment with its own package installation area.
uv and Python pin The tool managing Python/environments; an exact Python version recorded in .python-version.

Readiness checkpoint: Before moving into Django setup, explain a branch and a loop including the empty case; distinguish return from print; follow a module import and an instance-method call; and locate a failing operation in a traceback. On your own machine, record the uv and Python versions, current practice-directory path, expected and actual preview output, environment identity result, uv package-list result, and readiness result. Keep those observations in a plain-text file named readiness-notes.txt in the practice directory. Use your actual paths and results; there is no pre-filled claim of success.

If a language prediction is uncertain, return to that section’s short exercise. If a command fails, preserve the error and use the directory/interpreter checks before changing code. Completing only the paper work is useful progress, but the tools checkpoint is complete only after you run and explain the results on your machine. This chapter has prepared Python practice files, not a Django application or a verified registration feature.

Git Commit

There is nothing to commit. The practice folder is a workspace for this chapter, not the Otahque project, and Git arrives with the project in Chapter 8. Keep readiness-notes.txt as your own record.

PAGE 005

Test Your Knowledge: Interview Questions

These five questions rehearse the chapter at interview level, one at each of five levels from junior to lead. L1 and L2 check what you have just learned. L3 asks how it works underneath. L4 and L5 ask about the design and leadership decisions that later chapters build on: attempt them now, and return to them when you reach those chapters. Use the readiness checkpoint to decide whether to continue. If an answer is difficult, revisit its worked example and explain the result in your own words. L4 and L5 are extension questions, not a gate to the next chapter.

L1 (Junior): What is the difference between a list and a dictionary, and when would you use each?

What the interviewer is testing: Can you choose a collection by how its values will be found?

Flip to check your answerFold answer back

Perfect answer: A list is an ordered collection: you select an item by its position, counting from 0. A dictionary maps keys to values: you look a value up by its key. Use a list for a sequence of similar things, such as events in order, and a dictionary for the named facts about one thing, such as an event’s title and whether it is published. This chapter combines them as a list of dictionaries. When a key may be missing, get() returns a default instead of raising KeyError.

Table 4.7 — A list compared with a dictionary
Question List Dictionary
Written as ["Python Evening", "Testing Clinic"] {"title": "Python Evening"}
Select an item by Position, from 0 Key
Missing item IndexError KeyError, or a default with get()
Good for A sequence of similar things The named facts about one thing
A loop yields Each item Each key

Behind the scenes:

# titles[1]       -> go straight to position 1
# event["title"]  -> hash("title") picks the slot to check,
#                    so lookup by key does not scan every item
# "title" in titles would scan the list item by item

Code proof: in a file run with Python 3.14:

event = {"title": "Python Evening", "is_published": True}
titles = ["Python Evening", "Testing Clinic"]
print(titles[1])
print(event["title"])
print(event.get("venue", "Venue to be confirmed"))
Testing Clinic
Python Evening
Venue to be confirmed

Common mistakes:

  • Expecting index 1 to be the first item.
  • Misspelling a key and then reading the KeyError as a broken dictionary.
  • Using a list where looking up by name would be clearer.

Follow-up the interviewer might ask:

  • “How would you count the published events in a list of dictionaries?”
  • “What does len() return for each collection?”

L2 (Mid-Level): What does a function return if it has no return statement, and why does that matter?

What the interviewer is testing: Can you tell output that is displayed from a value that is returned?

Flip to check your answerFold answer back
Five numbered steps from top to bottom: call show_title with a title; print displays the title; the body ends without a return; the call evaluates to None; result now holds None.
Figure 4.7 — A function that only prints still returns a value: None.

Perfect answer: It returns None. print() displays text but gives nothing back to the caller, so storing the result of a function that only prints stores None. That matters as soon as the result is used: a label function that prints instead of returning leaves the caller with None to display or compare, and the mistake shows up far from its cause. Return the value, and let the caller decide whether to print it.

Behind the scenes:

# Every function call is an expression with a value.
# Reaching the end of the body is the same as `return None`.
# print() itself returns None after writing its text.

Code proof:

def show_title(title):
    print(title)

result = show_title("Python Evening")
print(result)
Python Evening
None

Common mistakes:

  • Confusing printed output with a return value.
  • Returning in one branch and forgetting the other.
  • Reading None as an error rather than as a value.

Follow-up the interviewer might ask:

  • “Change show_title so that the caller can use the title.”
  • “When is returning None the right design?”

L3 (Senior): Explain instance attributes, and why changing one object does not change another.

What the interviewer is testing: Do you understand what self refers to, and what the class and its instances each hold?

Flip to check your answerFold answer back
Five numbered steps from top to bottom: calling EventCard creates a new instance; __init__ runs with self as that object; self.title is stored on that instance; label() reads self.title; each instance keeps its own title.
Figure 4.8 — Creating an instance and storing its own attribute.

Perfect answer: Calling a class creates a new instance. Python runs __init__ with self referring to that new object, so self.title = title stores an attribute on that one instance. first and second each have their own title, so changing first.title leaves second.title alone (Figure 4.4). Methods are defined once, on the class, and shared: when you call first.label(), Python passes first as self. A value assigned on the class itself is different: it is shared by every instance until an instance assigns its own.

Behind the scenes:

# 1. Python creates a new, empty EventCard object
# 2. EventCard.__init__(that_object, "Python Evening") runs
# 3. self.title = ... stores into that object's own attributes
# first.label() is EventCard.label(first)

Code proof:

class EventCard:
    def __init__(self, title):
        self.title = title

    def label(self):
        return "Event: " + self.title

first = EventCard("Python Evening")
second = EventCard("Testing Clinic")
first.title = "Python Afternoon"
print(first.label())
print(second.label())
Event: Python Afternoon
Event: Testing Clinic

Common mistakes:

  • Thinking the class holds one title for all its instances.
  • Leaving out self.
  • Putting a list on the class and being surprised that every instance shares it.

Follow-up the interviewer might ask:

  • “What happens if the class defines titles = [] and each instance appends to it?”
  • “Why does label() need self?”

L4 (Staff): Why does every project need its own virtual environment, and how do you prove which Python and packages a project is using?

What the interviewer is testing: Can you explain isolation and verify an environment instead of assuming it?

Flip to check your answerFold answer back
Five numbered steps from top to bottom: create .venv with uv venv; .python-version records 3.14.9; run commands with --python .venv; print sys.executable and the two prefixes; rebuild the environment on each machine rather than copying it.
Figure 4.9 — Creating an environment and proving which one ran.

Perfect answer: A virtual environment gives a project its own place to install packages, so versions do not collide with another project or with the system’s Python, and the environment can be rebuilt from recorded versions. uv records the Python version in .python-version and creates .venv, and we select it with --python .venv. To prove it, print sys.executable, which should point inside .venv, and compare sys.prefix with sys.base_prefix, which differ inside a virtual environment; uv pip list --python .venv shows its packages. Rebuild an environment on each machine rather than copying the folder: it contains machine-specific paths.

Behind the scenes:

# uv venv writes .venv/pyvenv.cfg, naming the base Python.
# At startup, Python finds pyvenv.cfg beside its executable
# and sets sys.prefix to .venv; sys.base_prefix still names
# the base installation, so the two differ.

Code proof: with a file run by uv run --no-project --python .venv:

import sys

print(sys.executable)
print(sys.prefix != sys.base_prefix)
[a path inside your project's .venv folder]
True

Common mistakes:

  • Installing packages into the system’s Python.
  • Running one environment’s interpreter while believing another is selected.
  • Copying or sharing .venv.

Follow-up the interviewer might ask:

  • “How would a teammate rebuild your environment?”
  • “What is the difference between pinning a package and locking every dependency?”

L5 (Lead): You are onboarding three new contributors to a Python project. What do you standardize before they write code, and why?

What the interviewer is testing: Can you make a team’s results reproducible and its problems quick to diagnose?

Flip to check your answerFold answer back
Five numbered steps from top to bottom: one exact Python version; one tool for environments; one environment per project; a readiness script that fails loudly; a standard way to report a problem.
Figure 4.10 — What to standardize before a contributor’s first change.

Perfect answer: Standardize what makes results the same everywhere and errors easy to report: one exact Python version, recorded in the project; one tool for environments, such as uv; a separate environment per project; commands written for each platform; and a readiness script that stops loudly when something is wrong, like this chapter’s readiness.py. Agree how to report a problem: the command, the working directory, the full traceback, and the versions. Leave personal choices, such as the editor, to each person. Onboarding is finished when each contributor’s readiness check gives the expected output, before their first change.

Behind the scenes:

1. the Python version matches the pinned one
2. the interpreter is inside the project's environment
3. the project's own code imports
4. a few known inputs give known results
then print one clear success line, or fail at the first gap

Code proof: this chapter’s readiness program, run with the practice environment:

uv run --no-project --python .venv readiness.py
Readiness checks passed

Common mistakes:

  • Setup notes that say only “install Python”.
  • Standardizing personal preferences, such as the editor.
  • Onboarding without a verification step.

Follow-up the interviewer might ask:

  • “A contributor’s readiness check passes but the project still fails. What next?”
  • “What belongs in a README, and what in a script?”

Next: Chapter 5 explains Django’s role and records our first architecture decision, using the requirements from Chapters 1 and 2 and the web request journey from Chapter 3.

PAGE 006