Skip to contents
OpenLearningTHE STUDY LIBRARY

In depth study guide · Edition 2026.12

Python: From First Program to Reliable Tools

An illustrated, practice-first guide to thinking in Python and building a tested command-line application

A detailed original guide to Python values, program flow, functions, collections, files, modules, objects, testing, performance, and an integrated reading-ledger project.

16 chapters11 diagrams32 practice tasks

Before you begin

How to use this guide

Learners new to programming and developers who want a careful foundation before frameworks.

Helpful background

What you will be able to do

A useful study rhythm

Read the explanation, close the book, and draw or explain the idea from memory. Predict each example before running or tracing it. Attempt the chapter exercises, compare your reasoning with the solution manual, and return to the source when an assumption changes.

For a first pass, follow the chapter order. For revision, use the contents and glossary. Assessment answers and exercise solutions are separated from the questions so you can retrieve an answer before seeing it. Internal links and bookmarks work in most PDF readers; the printed page number helps when reading on paper.

Scope and assumptions

Core explanations and original diagrams are available offline. External books, videos, and documentation remain at their publishers’ sites and may require an internet connection or a separate account.

Chapter 01

Run, observe, and reason

Build a dependable workflow before adding language features.

By the end of this chapter
  • Separate editor, shell and interpreter
  • Run a saved script
  • Use output and errors as evidence

The three places beginners confuse

A program is a precise set of instructions applied to some state. Python source is ordinary text; an interpreter reads that text and carries out its meaning. Your editor changes the text, your terminal starts programs, and Python evaluates Python statements. Keep those three roles separate. Typing a terminal command such as python 3 hello.py at the Python prompt asks Python to interpret a command that belongs to the shell, so it fails before your intended script runs.

Create a dedicated learning folder and save hello.py inside it. In a terminal, move to that folder and run the file. On some systems the executable is named python rather than python 3; inspect the version before deciding. An integrated development environment can launch the same process, but the selected interpreter still matters. If a file appears to run old code, check the saved file, the current folder and the interpreter path before reinstalling anything.

Go deeper: [1] The Python 3.11 tutorial · [11] Python 3.11: virtual environments

Observe a small execution

Read a script as a sequence of actions, not as a picture to memorize. Before running the example, predict two output lines and their order. Python evaluates the arithmetic expression, binds the resulting integer to minutes, and calls print with that value. A comment describes intent for the reader; it does not change the calculation. Changing sessions from three to four should change one result without requiring a new program structure.

Interactive Python is useful for one uncertain expression, while a saved script preserves a repeatable experiment. Do not paste the displayed prompt characters into a file. When an example shows expected output, that output is evidence to compare with your run, not extra source to type. Keep a tiny notebook of predictions, actual results and explanations. The purpose is to improve your model of execution rather than accumulate screenshots of successful commands.

Save as hello.py, then run python 3 hello.py python · hello.py
sessions = 3
minutes_per_session = 25
minutes = sessions * minutes_per_session
print("Study minutes:")
print(minutes)
Expected result
Study minutes:
75

Go deeper: [2] Python 3.11: informal introduction

A repeatable learning loop

Mistakes are part of the feedback mechanism. A syntax error means Python could not understand the source structure; a later runtime error means execution reached an operation it could not complete. Read the final error line, locate the named source line, and reduce the program until you can describe the failing operation. Random edits can accidentally hide the symptom without correcting the misunderstanding that produced it.

Use a simple cycle throughout this book: predict, run, explain, vary, and test a boundary. Change only one relevant thing at first. If output surprises you, write down which assumption was wrong. Keep programs small enough to finish this cycle quickly. You do not need external packages for the core chapters, and you should not run an unfamiliar downloaded script merely because it claims to fix an installation problem.

The route from idea to evidenceThe learner writes a text file, launches Python, observes output and uses the result to revise the next prediction. The feedback arrow is a learning habit rather than an automatic program feature.PredictState the result you expectEditSave source in hello.pyRunStart the chosen interpreterObserveCompare output and errorsReviseExplain the difference before editing
The route from idea to evidence. The learner writes a text file, launches Python, observes output and uses the result to revise the next prediction. The feedback arrow is a learning habit rather than an automatic program feature.Scroll horizontally to read the full diagram on a small screen.

Go deeper: [5] Python 3.11: errors and exceptions · [22] CS 50 Introduction to Programming with Python: free video lectures

Keep these ideas

  • The editor writes source; the shell launches a process; Python executes statements.
  • Predicting output makes each small run a test of understanding.
  • Fix the first relevant failure at the layer where it occurs.

Practise before moving on

Try each task before opening the solution. Explain your reasoning, including a boundary or failure case.

1.1 · Practice task

Change the example to four sessions of twenty minutes. Predict both output lines before running it.

Hint: Keep the display label separate from the computed number.

Read the worked solution

1.2 · Practice task

A terminal reports that hello.py does not exist. Give three checks that are more useful than editing the arithmetic.

Hint: The failure happens before Python reads your calculation.

Read the worked solution

Chapter 02

Values, names, and numeric meaning

Understand assignment, comparison, conversion, and numerical limits.

By the end of this chapter
  • Trace rebinding
  • Distinguish text and numbers
  • Choose equality and identity correctly

Names, values, and object identity

A value is something the program can work with, such as an integer, a string or a list. An object has an identity, a type and a value; names are bindings that let your code refer to objects. In count = 7, assignment does not create a permanent box that can hold only integers. Later assignment can bind count to another object, although changing its meaning unpredictably makes a program difficult to understand.

Read assignment from the right: first evaluate the expression, then bind the name on the left. With first = 10 followed by second = first, both names initially refer to the integer value ten. Reassigning first to eleven does not update second. The same rule explains more surprising examples with mutable containers later. Avoid the misleading shortcut that assignment always copies an object's contents; whether something is copied is a separate question.

Go deeper: [2] Python 3.11: informal introduction · [4] Python 3.11: data structures

Numbers represent choices

Integers represent whole-number quantities without a fixed machine-width limit in ordinary Python arithmetic, although very large values still consume time and memory. The slash operator performs true division; two integers can therefore produce a floating-point result. Floor division rounds the quotient downward, which matters for negative inputs. Remainder is useful for grouping and divisibility, but you should verify the sign rules rather than importing assumptions from another language.

Floating-point values represent many real numbers approximately. A displayed decimal such as 0.1 does not imply an exact decimal fraction internally. This is not a Python defect: it follows from the finite representation used by ordinary floats. For measurements, use appropriate tolerances when comparing calculated results. For money, choose an explicit decimal or integer-minor-unit policy and specify rounding. Simply formatting a number to two decimals changes its presentation, not the earlier arithmetic.

Trace each numeric operation independently python
print(7 / 2)
print(7 // 2)
print(-7 // 2)
print(7 % 2)
first = 10
second = first
first = 11
print(first, second)
Expected result
3.5
3
-4
1
11 10

Go deeper: [2] Python 3.11: informal introduction · [21] Python 3.11: decimal arithmetic

Types and boundaries

The type of an object determines which operations make sense. Adding two integers performs arithmetic; adding two strings concatenates text. The text "12" and the integer 12 communicate different meanings even if they look similar on a screen. Convert at an input boundary after deciding what input is acceptable. int("12") succeeds, while int("twelve") raises ValueError; that distinction is useful information about the supplied data.

Use == when asking whether values compare equal. The is operator asks about identity, so it is appropriate for singleton checks such as value is None, not for comparing calculated numbers or names entered by a person. Do not infer general identity rules from a few interactive experiments: an implementation may reuse immutable objects. In daily program design, meaningful names and explicit conversions prevent more bugs than clever reliance on object reuse.

Rebinding leaves another name aloneBefore reassignment both names identify ten. Rebinding first to eleven changes its reference while second still identifies ten.Initial expression10 is evaluatedTwo bindingsfirst and second identify 10Rebind firstfirst now identifies 11Unchanged bindingsecond still identifies 10
Rebinding leaves another name alone. Before reassignment both names identify ten. Rebinding first to eleven changes its reference while second still identifies ten.Scroll horizontally to read the full diagram on a small screen.

Go deeper: [2] Python 3.11: informal introduction · [8] Python 3.11: built-in types

Keep these ideas

  • Assignment binds a name after evaluating an expression.
  • Value equality and object identity answer different questions.
  • Representation and rounding are design decisions, not display details.

Practise before moving on

Try each task before opening the solution. Explain your reasoning, including a boundary or failure case.

2.1 · Practice task

Predict the output after a = 4; b = a; a = a + 3; print(a, b). Explain each binding.

Hint: Evaluate the right-hand expression before changing a.

Read the worked solution

2.2 · Practice task

A price calculation must be exact in cents. Why is rounding a float only at print time an incomplete policy?

Hint: Presentation happens after calculation.

Read the worked solution

Chapter 03

Strings, input, and honest conversion

Treat text processing as a deliberate pipeline with visible assumptions.

By the end of this chapter
  • Use indexing and slices
  • Normalize without corrupting meaning
  • Keep parsing separate from evaluation

Text is a sequence with rules

A string is an immutable sequence of Unicode text. Indexing starts at zero, and a slice selects a range whose stop is excluded. Immutability means an operation does not rewrite the existing string object in place: methods such as strip and lower return new strings. If you call name.strip() and ignore the result, a later use of name still sees its original binding. Keep transformations visible by assigning the result to a clearly named variable.

For basic English examples, one indexed string element often looks like one visible character. Real text is less simple: combining marks and emoji sequences can use several code points for one perceived symbol. Therefore len(text) measures the string's code points, not a universal count of visible letters. Do not build a password length policy or display-column layout from a convenient classroom assumption without studying the requirements of real text.

Go deeper: [2] Python 3.11: informal introduction · [8] Python 3.11: built-in types

Input is untrusted text

input returns a string, even when someone types digits. Separate reading a value from interpreting it. First normalize only the features your domain allows, such as surrounding whitespace; then validate and convert. Do not silently remove every unexpected character from a numeric entry, because "12x" becoming 12 can hide a real mistake. An empty input can mean missing information rather than zero, so decide its meaning before calling a converter.

F-strings combine literal text and evaluated expressions in a readable way. Formatting can choose a decimal display or align columns, but it does not validate a value or change its mathematical meaning. Keep user-entered data as data. eval is not a shortcut for parsing a number; it evaluates Python expressions and can execute dangerous operations. Later chapters use explicit converters and structured data parsers so the accepted language stays narrow.

Normalize a topic without evaluating user text python
raw_topic = "  Python Basics  "
topic = raw_topic.strip()
lookup_key = topic.casefold()
print(f"Topic: {topic}")
print(lookup_key)
print(topic[:6])
print(repr("line one\nline two"))
Expected result
Topic: Python Basics
python basics
Python
'line one\nline two'

Go deeper: [6] Python 3.11: input and output · [9] Python 3.11: built-in functions

A transformation pipeline

Suppose a learner types a topic with spaces and inconsistent capitalization. Store the original text if presentation matters, and derive a normalized lookup key separately. Normalization is a domain rule: lowercasing identifiers may be useful, while changing the case of a case-sensitive password or filesystem path can break the intended meaning. For case-insensitive comparisons across languages, casefold is often more suitable than assuming lower handles every script.

Build transformations as small named steps, then test representative and awkward inputs. Include an empty string, only whitespace, punctuation and non-English text. Escaping a newline in a Python literal and receiving a literal backslash followed by n from a file are different situations; inspect repr(value) when invisible characters are confusing. Clear observation avoids replacing random characters until the example happens to look right.

From input text to domain valueThe raw input is kept separate from the normalized form. Validation decides whether conversion should proceed; display uses the validated result.ReadReceive a stringNormalizeApply permitted whitespace or case rulesValidateCheck allowed form and rangeConvertProduce the domain valuePresentFormat a helpful result
From input text to domain value. The raw input is kept separate from the normalized form. Validation decides whether conversion should proceed; display uses the validated result.Scroll horizontally to read the full diagram on a small screen.

Go deeper: [8] Python 3.11: built-in types · [6] Python 3.11: input and output

Keep these ideas

  • Strings are immutable; keep returned transformations.
  • Input begins as text and must cross an explicit validation boundary.
  • Unicode code points and visible characters are different concepts.

Practise before moving on

Try each task before opening the solution. Explain your reasoning, including a boundary or failure case.

3.1 · Practice task

Why does word = " Java "; word.strip(); print(word) still include spaces? Repair it.

Hint: Ask whether strip mutates a string.

Read the worked solution

3.2 · Practice task

Design a minutes input rule that accepts surrounding spaces and nonnegative whole numbers but rejects empty text and 12x.

Hint: Normalization, conversion and range checking are separate decisions.

Read the worked solution

Chapter 04

Conditions and boundary thinking

Turn a requirement into explicit, testable decisions.

By the end of this chapter
  • Partition a valid input range
  • Explain short-circuit behavior
  • Distinguish missing from zero

Conditions select a path

An if statement executes its body when its condition is true; elif considers another condition only if the earlier choices were false. An else handles the remaining case. Indentation is part of Python's syntax, so the visual block and the executed block must agree. Express one business decision at a time. A complicated expression that technically works can still be hard to verify when it combines unrelated permission, validation and calculation rules.

Comparison operators produce Boolean results, and and, or and not combine conditions using short-circuit rules. Short-circuiting can guard an operation: a value is not divided by zero if a preceding and condition already rules out that path. However, and and or return one of their operands, not necessarily a Boolean. This makes idioms concise but can confuse beginners who assume every condition expression yields exactly True or False.

Go deeper: [3] Python 3.11: control flow and functions · [8] Python 3.11: built-in types

Boundaries reveal missing cases

For a score classifier, decide whether the endpoints belong to the interval before writing code. If ninety and above means distinction, test 89,90 and 91. A rule based on greater-than rather than greater-than-or-equal changes the boundary. Also test values outside the permitted domain; a classifier should not award a category to a score of 500 merely because it satisfies the highest threshold. Validation and classification solve different problems.

Put broad validity checks before the meaningful categories, then arrange thresholds so each accepted input reaches one intended branch. Trace a table rather than eyeballing the source. A truth table can expose that an or condition accepts almost everything, or that an and condition can never be true. Good branches communicate the domain's partition of possible inputs, and tests confirm the partitions meet at their boundaries without unintended gaps.

Validate before classifying a result python
def category(score):
    if not 0 <= score <= 100:
        raise ValueError("score must be between 0 and 100")
    if score >= 90:
        return "distinction"
    if score >= 60:
        return "pass"
    return "practice needed"

for score in (59, 60, 89, 90):
    print(score, category(score))
Expected result
59 practice needed
60 pass
89 pass
90 distinction

Go deeper: [3] Python 3.11: control flow and functions

Truthiness is useful and contextual

Empty containers, empty strings, numeric zero, None and False are false in Boolean contexts. That permits readable checks such as if not records when an empty collection needs special handling. But if not value treats several distinct states alike. If zero is a valid observed measurement and None means missing data, use an explicit None check. A convenient truthiness test must not erase a distinction the domain needs to preserve.

Prefer early returns or clear branches over deeply nested pyramids. A function can reject invalid input first and then perform its normal work with fewer indentation levels. Do not optimize for the smallest line count: someone must later explain why a request was accepted. Use parentheses around mixed conditions when they clarify the grouping, and name a complex condition if its business meaning is more important than its syntax.

Go deeper: [3] Python 3.11: control flow and functions · [9] Python 3.11: built-in functions

Keep these ideas

  • Check validity separately from classification.
  • Use boundary examples to test the meaning of comparisons.
  • Short-circuit logic helps only when its accepted states match the domain.

Practise before moving on

Try each task before opening the solution. Explain your reasoning, including a boundary or failure case.

4.1 · Practice task

For an inclusive range 1 to 10, why is n >= 1 or n <= 10 wrong? Give a counterexample.

Hint: Try a value below the lower bound.

Read the worked solution

4.2 · Practice task

A sensor returns 0 for no movement and None for a missing reading. Write the conceptual decision without merging those states.

Hint: Use identity for the missing singleton.

Read the worked solution

Chapter 05

Loops that you can prove will finish

Trace iteration, protect boundaries, and count work.

By the end of this chapter
  • State a loop invariant
  • Handle empty input
  • Explain termination and nested work

Iteration and an invariant

A loop repeats a body over changing state. In a for loop, Python obtains successive values from an iterable and binds the loop variable to each one. A useful way to reason about the loop is an invariant: a statement that remains true before and after each iteration. In a running total, the total equals the sum of the already-processed values. The invariant is more informative than the vague instruction to keep adding things.

Before writing the body, identify the initial state, what one step does and when processing ends. For an empty input, the body runs zero times, so the initial state determines the result. If a minimum calculation begins at zero, it may incorrectly report zero for a list of positive numbers. Choose an initial value that matches the operation, or handle the first element and empty case explicitly.

The running-total invariantThe total begins at zero, adds only the current accepted value and returns to the next item. At every step it represents only the accepted prefix already processed.Initializetotal = 0; no items processedReceiveRead the next itemValidateReject a negative durationAccumulateAdd this accepted durationFinishNo items remain; total is the sum
The running-total invariant. The total begins at zero, adds only the current accepted value and returns to the next item. At every step it represents only the accepted prefix already processed.Scroll horizontally to read the full diagram on a small screen.

Go deeper: [3] Python 3.11: control flow and functions

Ranges and controlled repetition

range produces a sequence-like iterable of integers with an excluded stop value. range(4) visits 0 through 3. This fits indexing because a four-item list has those valid nonnegative indices, but direct iteration is usually clearer when you only need the elements. Use enumerate when both an index and a value are meaningful, rather than keeping a separate counter that can drift away from the collection.

A while loop repeats while its condition remains true, so it needs a clear progress argument. If a failed input does not change the state, the loop may never end. When an operation is bounded by a retry policy, represent the bound explicitly rather than hoping success eventually occurs. break exits the nearest loop; continue skips the rest of the current iteration. Both can clarify exceptional cases, but too many exits make a trace harder to follow.

Trace a filtered total python
minutes = [25, -2, 40, 0]
total = 0
for index, value in enumerate(minutes, start=1):
    if value < 0:
        continue
    total += value
    print(index, total)
print("Accepted total:", total)
Expected result
1 25
3 65
4 65
Accepted total: 65

Go deeper: [3] Python 3.11: control flow and functions

Avoid hidden work and structural mutation

Nested loops multiply work. If an outer loop visits every learner and an inner loop visits every book, doubling both input sizes can roughly quadruple the number of pairs examined. That may be appropriate for a deliberate pairwise task, but it is wasteful for repeated membership checks that a set can answer directly. Count what the algorithm does before reaching for a faster computer or a shorter syntax.

Do not casually add or remove items from a list while iterating over that same list. Indices shift and items can be skipped, creating behavior that depends on mutation timing. Build a new collection of accepted items, or iterate over a separate snapshot when mutation is truly required. Make each iteration's responsibility small, then trace the first step, the final step and an empty input. Those cases expose many off-by-one and initialization errors.

Go deeper: [3] Python 3.11: control flow and functions · [4] Python 3.11: data structures

Keep these ideas

  • An invariant explains what the accumulated state means.
  • The empty case is determined before the first iteration.
  • A terminating loop needs progress toward a bounded end.

Practise before moving on

Try each task before opening the solution. Explain your reasoning, including a boundary or failure case.

5.1 · Practice task

Compute the largest of several positive measurements. Explain why initializing largest to 0 is still an incomplete general design.

Hint: Ask what empty or all-negative inputs mean.

Read the worked solution

5.2 · Practice task

Filter values greater than or equal to 0 without removing items from the list being traversed.

Hint: Build a result list instead of changing the traversal structure.

Read the worked solution

Chapter 06

Functions, contracts, and scope

Build operations that can be reused and tested without hidden interaction.

By the end of this chapter
  • Distinguish return from print
  • Trace mutation across calls
  • Avoid mutable defaults

A contract for a small operation

A function packages an operation behind a name, parameters and a result. Treat its signature as the start of a contract: which inputs are accepted, what result is produced and which failures are reported. A parameter is a local name in the definition; an argument is a value supplied by the caller. Returning a value lets another operation use it. Printing is an output effect and does not substitute for a useful return value.

Keep calculations separate from input and display. A function that asks a question through input every time it runs is difficult to test automatically and awkward to reuse in a web service or file-processing tool. A function that receives data and returns a result can be called from any of those places. Put environment-specific interaction at the program's edges, where you can explain and test it independently.

A calculation with explicit edgesInput parsing and display sit outside the calculation. The calculation receives already-understood values and returns a result, which makes it usable from different interfaces.Read and parseTurn external text into valuesCall calculationPass explicit argumentsComputeUse local state and a clear contractReturnProduce a value or an explicit failurePresentChoose how to display the outcome
A calculation with explicit edges. Input parsing and display sit outside the calculation. The calculation receives already-understood values and returns a result, which makes it usable from different interfaces.Scroll horizontally to read the full diagram on a small screen.

Go deeper: [3] Python 3.11: control flow and functions

Bindings inside a call

Each call creates a new local namespace for its parameters and local variables. Rebinding a parameter does not rebind the caller's variable. However, a parameter can refer to the same mutable object as the caller, so mutating that object can be observed outside the function. This is the same binding model from the values chapter, not a separate magic rule for function arguments. State whether a function mutates supplied containers.

Default argument expressions are evaluated when the function is defined. A mutable default such as an empty list can therefore be shared across calls, which is often accidental. Use None as a sentinel and create a new list inside the call when each invocation needs independent storage. Avoid changing global variables to return information; globals hide inputs and make one call's behavior depend on earlier calls in ways the signature does not reveal.

Return a result and avoid shared defaults python
def append_note(note, notes=None):
    if notes is None:
        notes = []
    notes.append(note)
    return notes

def average(values):
    if not values:
        return None
    return sum(values) / len(values)

print(append_note("read"))
print(append_note("review"))
print(average([20, 40]))
print(average([]))
Expected result
['read']
['review']
30.0
None

Go deeper: [3] Python 3.11: control flow and functions · [7] Python 3.11: classes and iterators

Design before generalizing

A good name describes the domain operation, such as average_minutes or normalize_title. Explain the empty case in the contract. Returning None for an undefined average differs from returning zero, because zero can be a real measured average. A caller should handle the absence deliberately rather than unexpectedly adding None to a number. Type annotations and documentation can communicate that result, while tests show concrete examples.

Do not turn every repeated line into a general framework immediately. First identify a stable responsibility, write the clearest small function and call it in two realistic contexts. If its parameters become unrelated switches, it may be doing too much. Debug by checking the inputs and return value at a function boundary. Smaller contracts reduce the number of possible places where an incorrect result can originate.

Go deeper: [3] Python 3.11: control flow and functions · [18] Python 3.11: type hints

Keep these ideas

  • A function exposes accepted inputs and a result policy.
  • Parameter rebinding and object mutation are different operations.
  • Pure calculations simplify testing and reuse.

Practise before moving on

Try each task before opening the solution. Explain your reasoning, including a boundary or failure case.

6.1 · Practice task

A function prints a total and the caller prints the function call. Why does None appear after the total?

Hint: What value does the function return explicitly?

Read the worked solution

6.2 · Practice task

Write a contract for average([]) and give one acceptable implementation policy.

Hint: An absent average is not automatically zero.

Read the worked solution

Chapter 07

Lists, tuples, copies, and ownership

Choose sequence operations by their meaning and mutation behavior.

By the end of this chapter
  • Predict aliasing
  • Distinguish shallow from nested copies
  • Select in-place or returned operations

Sequence choices and meaning

Lists store an ordered sequence that can change over time. Tuples are also ordered, but their item references cannot be reassigned in place. A tuple can still refer to a mutable object, so immutability of the outer structure is not a guarantee that every reachable value is frozen. Choose a list for a growing queue of records and a tuple when a fixed grouping communicates the meaning more clearly.

Indexing answers a position-based question and raises IndexError when a requested position is outside the sequence. Slicing selects a range and normally returns a new outer sequence. Negative indices count from the end, which can express last-item operations clearly. However, clever chains of slices can obscure the rule. Prefer a descriptive intermediate name when a reader would otherwise need to decode three transformations in one expression.

Go deeper: [4] Python 3.11: data structures · [8] Python 3.11: built-in types

Aliasing, copying, and mutation

Two variables can refer to the same list. Appending through one variable changes that list, so the other variable observes the new contents. A shallow copy creates a new outer container while retaining references to the same nested elements. If those elements are lists or dictionaries, mutating one nested element can still be seen through both outer containers. Draw the references when a printed result is surprising; the diagram usually explains it immediately.

Not every method returns the changed container. list.sort rearranges the list in place and returns None, while sorted builds a new sorted list from an iterable. Decide whether the original ordering must be preserved before choosing one. A copy is not a universal fix for unclear ownership: copying everything can consume memory and still leave nested mutation shared. Define which function or component is allowed to change each structure.

See the difference between an outer copy and nested sharing python
original = [[1], [2]]
copy = original.copy()
copy.append([3])
copy[0].append(9)
print(original)
print(copy)
values = [3, 1, 2]
ordered = sorted(values)
print(values, ordered)
Expected result
[[1, 9], [2]]
[[1, 9], [2], [3]]
[3, 1, 2] [1, 2, 3]

Go deeper: [4] Python 3.11: data structures

Practical sequence patterns

Unpacking gives a name to each part of a known grouping, which can be clearer than repeated numeric indexing. Use zip for corresponding items only after deciding what unequal lengths mean; ordinary zip stops when the shortest input ends. If a business rule requires equal lengths, validate them first rather than silently dropping unmatched data. A neat-looking loop can still implement the wrong data rule.

For a small collection, readability often matters more than microscopic speed differences. As data grows, the choice of operation matters: repeatedly inserting at the front of a list moves existing references, and repeated membership scans inspect many values. Later chapters introduce sets and measurement. First make the structure's meaning explicit, then test empty, single-item and repeated-item inputs so the expected ordering and mutation behavior are visible.

Go deeper: [4] Python 3.11: data structures · [9] Python 3.11: built-in functions

Keep these ideas

  • A tuple can contain references to mutable values.
  • A shallow copy separates only the outer container.
  • Choose mutation deliberately and document ownership.

Practise before moving on

Try each task before opening the solution. Explain your reasoning, including a boundary or failure case.

7.1 · Practice task

Why does result = values.sort() usually make result None? Give an alternative that preserves values.

Hint: Compare an in-place operation with a transformation.

Read the worked solution

7.2 · Practice task

You have two names for the same list. How can you verify whether an append through one is visible through the other?

Hint: Trace references, then run a minimal example.

Read the worked solution

Chapter 08

Dictionaries, sets, and data questions

Represent lookup, counting, grouping, and distinct membership honestly.

By the end of this chapter
  • Choose mapping or set semantics
  • Handle missing keys explicitly
  • Separate counting from display order

Lookup keys versus positions

A dictionary maps unique hashable keys to values. Use it when the important question is which value belongs to this identifier, rather than which value is in position three. Looking up a missing key with square brackets raises KeyError, which is appropriate when absence violates an assumption. get can supply a default when absence is expected. Do not choose a default that erases a meaningful distinction between missing data and an observed zero.

A set stores distinct hashable values and supports membership, union, intersection and difference. Sets are useful for deduplication and comparing groups, but their iteration order is not a presentation contract. Sort values before displaying a deterministic report. Dictionaries preserve insertion order in the targeted Python versions, yet their order should still follow the report's requirements rather than the incidental order of an uncontrolled input source.

Go deeper: [4] Python 3.11: data structures · [8] Python 3.11: built-in types

Count and group deliberately

Counting topics is a small example of translating a domain question into a data structure. The key is the normalized topic and the value is its count. For every accepted record, obtain the previous count and add one. State the normalization policy first: Python and python may describe the same topic in your application, while two different course identifiers must remain distinct. A dictionary cannot decide which textual differences are meaningful.

Do not change a key's logical equality while it is being used for lookup. Built-in mutable lists and dictionaries are unhashable, which prevents common forms of this problem. Tuples can be keys only when all their elements are hashable. Custom key objects require a consistent equality and hash policy; beginners should prefer stable primitive identifiers until they understand that contract. A hash is a lookup aid, not a unique identity certificate.

Count normalized topics and compare groups python
topics = ["Python", " python ", "Java"]
counts = {}
for topic in topics:
    key = topic.strip().casefold()
    counts[key] = counts.get(key, 0) + 1
for topic in sorted(counts):
    print(topic, counts[topic])
planned = {"python", "java", "sql"}
visited = set(counts)
print(sorted(planned - visited))
Expected result
java 1
python 2
['sql']

Go deeper: [4] Python 3.11: data structures · [8] Python 3.11: built-in types

Tradeoffs and boundary cases

An average-case fast lookup is not a promise that every operation takes identical time, and a set is not automatically the right representation for every task. Converting a sequence to a set loses repeated occurrences and positional order. If a reading history contains three sessions on the same book, deduplicating titles answers which books appeared, not how many sessions occurred. Write the exact question beside the chosen representation.

Test missing keys, repeated records, inconsistent capitalization and an empty collection. For a report, define deterministic ordering separately from counting. For merging data, decide whether a later value replaces an earlier one, duplicates are rejected, or values are combined. Updating a dictionary without an explicit collision policy can quietly discard data. Data structures make operations convenient; the application still owns the meaning of those operations.

Count, then presentNormalization produces stable keys, a dictionary accumulates counts, and a separate sorted traversal determines display order. Counting and presentation are different responsibilities.Raw topicsPython, python, JavaNormalize keysApply the documented case ruleCount in a mappingOne integer per normalized topicChoose display orderSort keys for a repeatable report
Count, then present. Normalization produces stable keys, a dictionary accumulates counts, and a separate sorted traversal determines display order. Counting and presentation are different responsibilities.Scroll horizontally to read the full diagram on a small screen.

Go deeper: [4] Python 3.11: data structures · [9] Python 3.11: built-in functions

Keep these ideas

  • Mappings answer key-based questions; sequences answer position-based questions.
  • Sets remove duplicate values and do not preserve a presentation order.
  • Missing-key and duplicate-key policies belong to the application.

Practise before moving on

Try each task before opening the solution. Explain your reasoning, including a boundary or failure case.

8.1 · Practice task

A report turns every session title into a set and then counts the set. Which question is it answering, and which information did it lose?

Hint: Distinct values and occurrences are different measures.

Read the worked solution

8.2 · Practice task

A dictionary already contains a learner ID when a new record with the same ID arrives. Name three reasonable policies and choose one for an import tool.

Hint: Assignment will otherwise replace the old value.

Read the worked solution

Chapter 09

Comprehensions, iterators, and generators

Choose eagerly stored results or progressive computation deliberately.

By the end of this chapter
  • Trace iterator consumption
  • Use a readable comprehension
  • Explain lazy failure timing

An iterable is a source of successive values

An iterable can provide an iterator; an iterator supplies successive values until it is exhausted. A list is an iterable that keeps its elements available for repeated traversal. A generator iterator usually computes the next value only when requested and remembers enough state to resume. This distinction matters when input is large or arrives gradually. You can process one record at a time without first building a list containing every transformed record.

Laziness changes when work happens, not the meaning you should promise. An exception inside a generator may occur during iteration rather than when the generator object is created. Once exhausted, a generator does not automatically restart. If two later operations both need all the results, you must choose between regenerating the values and storing them. Do not advertise memory savings while immediately converting every generator to a large list.

A lazy pipelineA consumer requests one value, the generator examines its source until a suitable result is available, and only then returns control. This can limit retained intermediate data.Source iterableValues are available over timeGenerator stateResume from the previous yieldFilter and transformProduce one accepted valueConsumerAsk for the next value when needed
A lazy pipeline. A consumer requests one value, the generator examines its source until a suitable result is available, and only then returns control. This can limit retained intermediate data.Scroll horizontally to read the full diagram on a small screen.

Go deeper: [3] Python 3.11: control flow and functions · [7] Python 3.11: classes and iterators

Comprehensions express simple transformations

A list comprehension combines iteration, an optional filter and a result expression. It is a readable choice for a short transformation such as squaring accepted numbers. A dictionary comprehension builds key-value associations and a set comprehension builds distinct values. The result type changes the semantics: a set can remove duplicates and a dictionary can replace earlier entries with the same key. Compact syntax does not remove the need for a collision or ordering policy.

Keep complicated validation, error handling and multiple side effects in a named function or ordinary loop. Several nested comprehensions can hide the amount of work and the order of evaluation. A good test is whether you can read the expression aloud without losing track of which variable belongs to which source. If not, expand it. Clarity in a small pipeline is more useful than proving that everything can fit on one line.

Go deeper: [4] Python 3.11: data structures

A generator with a visible contract

The example yields only nonnegative durations. It does not cache earlier results and it does not know what later consumers will do. Each next request resumes the loop until it finds another accepted value or reaches the end. That makes it suitable for connecting a record reader to a calculation. If the source itself is expensive or stateful, document whether it can be traversed again and who is responsible for closing any associated resources.

Build a tiny trace before combining many lazy stages. First inspect one generated value, then consume the remainder and explain why the first value is no longer present. Test empty input, all-rejected input and a failure halfway through the source. Streaming does not mean errors cannot occur, and a partial report can be misleading if the tool prints a success message before all required input has been validated.

A generator is consumed progressively python
def accepted_minutes(values):
    for value in values:
        if value >= 0:
            yield value

stream = accepted_minutes([10, -1, 20])
print(next(stream))
print(list(stream))
print(list(stream))
print([n * n for n in range(5) if n % 2 == 0])
Expected result
10
[20]
[]
[0, 4, 16]

Go deeper: [3] Python 3.11: control flow and functions · [6] Python 3.11: input and output

Keep these ideas

  • Iterables provide traversal; iterators maintain traversal state.
  • Generators trade retained results for one-pass behavior and deferred work.
  • Short comprehensions are useful; dense side effects deserve explicit control flow.

Practise before moving on

Try each task before opening the solution. Explain your reasoning, including a boundary or failure case.

9.1 · Practice task

Why can sum(stream) followed by list(stream) produce a total and then an empty list?

Hint: Both operations consume the same iterator.

Read the worked solution

9.2 · Practice task

Rewrite a dense comprehension that validates data, prints warnings and computes a result. Which parts should become a loop or helper?

Hint: An expression should not hide several effects.

Read the worked solution

Chapter 10

Exceptions, tracebacks, and debugging

Make failure visible, specific, and recoverable where recovery is justified.

By the end of this chapter
  • Read a traceback
  • Keep handlers narrow
  • Distinguish validation from assertions

An exception is a reported failure

Python reports many failures by raising an exception. A traceback shows a chain of active calls and the point where the failure was raised. Start with the exception type and final message, then inspect the relevant source line and its actual values. The line that crashes is not always where the bad value originated. Trace backward through function contracts until you find the earliest assumption that did not hold.

Catch an exception when your code can make a specific useful decision: request corrected input, add domain context, use a documented fallback or stop with a helpful message. Catching every Exception and returning zero makes missing files, invalid records and programming mistakes look identical. The program may continue while producing believable but false output, which is often more damaging than an honest failure.

Go deeper: [5] Python 3.11: errors and exceptions

Keep the protected operation narrow

A try block should surround the operation whose failure you expect. If you only intend to handle a failed integer conversion, do not wrap an entire report generator in the same ValueError handler. A different ValueError from a later programming mistake might then be mislabeled as bad user input. Handle errors at the boundary that has enough context to explain what the user can do, while allowing unrelated defects to remain visible during development.

Use finally for cleanup that must be attempted whether the protected work succeeds or fails. Prefer a context manager such as with for resources whose lifecycle it expresses directly. Raising a new exception from an earlier one can preserve causal information while adding meaning. Do not expose private credentials or raw sensitive records in error messages merely to make debugging easier; log the minimal context needed to locate the failure.

Handle conversion failure without swallowing unrelated bugs python
def parse_minutes(text):
    try:
        value = int(text)
    except ValueError as error:
        raise ValueError("minutes must be a whole number") from error
    if value < 0:
        raise ValueError("minutes must not be negative")
    return value

print(parse_minutes(" 25 "))
try:
    parse_minutes("twenty")
except ValueError as error:
    print(error)
Expected result
25
minutes must be a whole number

Go deeper: [5] Python 3.11: errors and exceptions · [6] Python 3.11: input and output

Debug systematically

When an example misbehaves, reproduce it with the smallest input that still demonstrates the problem. State expected and actual behavior, inspect intermediate values using repr when whitespace or types are unclear, and change one assumption at a time. Temporary diagnostic prints can be useful, but remove or replace them with deliberate logging after understanding the cause. A debugger lets you pause at a line and inspect local state without guessing.

Turn a fixed defect into a regression test so the discovered case remains part of the program's specification. Assertions are useful for checking internal assumptions during development, but they can be disabled under optimization and are not input validation. A malformed uploaded record must be rejected through normal control flow even when assertions are absent. Error handling is part of the public contract and deserves tests alongside successful examples.

Go deeper: [5] Python 3.11: errors and exceptions · [17] Python 3.11: unittest

Keep these ideas

  • Handle failures only where a specific response makes sense.
  • Preserve the cause while adding useful context.
  • A regression test turns a discovered defect into a lasting specification.

Practise before moving on

Try each task before opening the solution. Explain your reasoning, including a boundary or failure case.

10.1 · Practice task

An import tool catches every Exception and prints Imported successfully. Explain two separate harms.

Hint: Think about both the user and the developer.

Read the worked solution

10.2 · Practice task

A test reveals that an empty filename was accepted unexpectedly. What should accompany the code fix?

Hint: Preserve the discovery as executable evidence.

Read the worked solution

Chapter 11

Files, JSON, CSV, and data integrity

Read structured data without confusing successful parsing with valid meaning.

By the end of this chapter
  • Use context managers
  • Validate a decoded schema
  • Plan safe writes and I/O tests

Resources and text encoding

A file combines external state with a resource lifecycle. Opening it may fail because it is missing, inaccessible or not a regular readable file; reading can fail later as well. A with block arranges for the file object to close when control leaves the block, including when an exception escapes. Do not assume that eventual garbage collection is a timely resource-management strategy.

Choose an encoding explicitly when your file format defines one. UTF-8 is a common portable choice for text, but arbitrary bytes are not automatically valid UTF-8. Distinguish a filesystem problem from a decoding problem so the message points to the right repair. A path is a location description, not the file contents. pathlib makes many path operations clearer, while the operating system still decides permissions, naming and actual I/O behavior.

Go deeper: [6] Python 3.11: input and output · [15] Python 3.11: pathlib

Structured formats have schemas

JSON represents objects, arrays, strings, numbers, booleans and null with a defined syntax. json.load handles that syntax; it does not prove that a decoded object matches your application's record rules. A document can be valid JSON yet contain a negative duration or an unexpected top-level string. Validate the overall shape and each field before performing calculations. Treat unknown or missing fields according to an explicit compatibility policy.

CSV is not reliably parsed by splitting every line on a comma. Quoted fields can contain commas, quotation marks and line breaks. Use the csv module with an agreed dialect, header policy and newline handling. The parser returns text values, so numeric columns still need conversion and validation. File size and row-count limits matter for untrusted input; a correct parser does not by itself prevent a user from supplying more data than your tool can safely process.

Parse CSV with its real parser python
import csv
import io

source = io.StringIO('title,minutes\n"Networks, gently",30\nPython,25\n')
rows = list(csv.DictReader(source))
total = sum(int(row["minutes"]) for row in rows)
print(rows[0]["title"])
print(total)
Expected result
Networks, gently
55

Go deeper: [13] Python 3.11: JSON · [14] Python 3.11: CSV

Avoid partial or destructive writes

Writing directly over an important file can leave it truncated if the process fails halfway through. For a small local tool, a common improvement is to write a complete temporary file in the same directory, close it, and then replace the intended destination. This helps avoid readers seeing a partially written document, but exact durability and replacement behavior depend on the filesystem and operating system. Backups and recovery rules remain separate concerns.

Keep a calculation function independent of file paths so it can be tested with an in-memory collection. Add I/O tests with temporary directories rather than overwriting a real personal document. Include empty files, malformed syntax, missing required fields, Unicode text and invalid numeric values. A useful importer reports which record failed and does not silently label a partially processed dataset as complete.

Syntax validation is not domain validationA file must first be decoded and parsed into values. Only then can the application verify fields and ranges before computing a trustworthy report.Read bytesCheck resource and size policyDecode and parseApply the chosen file formatValidate schemaCheck records, fields and typesValidate domainCheck ranges and duplicate policyCompute and reportUse only accepted records
Syntax validation is not domain validation. A file must first be decoded and parsed into values. Only then can the application verify fields and ranges before computing a trustworthy report.Scroll horizontally to read the full diagram on a small screen.

Go deeper: [15] Python 3.11: pathlib · [13] Python 3.11: JSON · [17] Python 3.11: unittest

Keep these ideas

  • Close resources with explicit lifecycle constructs.
  • Parsing validates format; application validation supplies meaning.
  • Protect important files from incomplete writes and test failure paths.

Practise before moving on

Try each task before opening the solution. Explain your reasoning, including a boundary or failure case.

11.1 · Practice task

The text {"minutes": -7} is valid JSON. Why must the import still reject it for a nonnegative-duration domain?

Hint: Syntax and business rules are independent.

Read the worked solution

11.2 · Practice task

Why does splitting a CSV line on commas corrupt the title "Networks, gently"?

Hint: A comma inside a quoted field is part of the field.

Read the worked solution

Chapter 12

Modules, environments, and command-line tools

Package small responsibilities without hiding startup or dependency assumptions.

By the end of this chapter
  • Avoid import side effects
  • Explain an environment
  • Design a clear CLI boundary

Modules keep responsibilities visible

A module is a Python source unit with its own namespace. Importing it makes its definitions available to another module and normally executes its top-level code on the first import in a process. That is why a utility module should not unexpectedly ask for input, delete a file or launch a long-running report as an import side effect. Put reusable calculations in functions and deliberate application startup behind a main guard.

An import name can accidentally resolve to your own file instead of the intended standard library. Naming a script json.py, for example, can confuse imports of json from that project. When a library behaves strangely, inspect the module location and interpreter rather than assuming the official module is broken. Organize a small project into a few meaningful responsibilities before adding a deep hierarchy of packages.

A small application boundaryThe command entry point translates arguments and errors. Reusable application functions own domain behavior, while standard-library adapters perform I/O when needed.Command entry pointParse arguments; choose exit statusApplication operationCoordinate validation and calculationDomain functionsReturn deterministic resultsI/O adapterRead or write explicit resources
A small application boundary. The command entry point translates arguments and errors. Reusable application functions own domain behavior, while standard-library adapters perform I/O when needed.Scroll horizontally to read the full diagram on a small screen.

Go deeper: [10] Python 3.11: modules

Environments and dependencies

A virtual environment gives a project its own installed package set built on a chosen Python installation. It is useful for avoiding accidental dependency mixing between projects, not for hiding application source or acting as a security boundary. Keep the environment directory out of version control and record enough configuration to recreate it. Use the environment's interpreter to run pip so installation and execution refer to the same Python.

This guide's programs need only the standard library. For future third-party dependencies, add a package because the project needs it, read its documentation and license, and record compatible versions. A copied requirements file does not guarantee that every platform receives the same low-level binaries or behavior. Test installation and execution in the environment you intend to support rather than treating a successful installation message as proof of application correctness.

Go deeper: [11] Python 3.11: virtual environments · [12] Python Packaging User Guide

A command-line boundary

A command-line interface should explain accepted arguments, reject malformed input and return a meaningful exit status. argparse handles many mechanics, including help text and basic conversion, while your program still checks domain rules. A file argument can be syntactically valid but refer to a missing or malformed dataset. Keep command parsing outside the calculation so the same function remains useful from tests or a future graphical interface.

Use a small main function that receives arguments, calls the application operation and returns an integer status. A main guard can pass that result to SystemExit. Print normal output to standard output and diagnostics to standard error when composing shell tools. The exact messages and statuses are part of the user's interface: give a repairable reason for failure, and avoid burying it under an enormous traceback for an expected input mistake.

A reusable module with an explicit command boundary python · total.py
import argparse

def total_minutes(values):
    if any(value < 0 for value in values):
        raise ValueError("minutes must not be negative")
    return sum(values)

def main(argv=None):
    parser = argparse.ArgumentParser(description="Total study minutes")
    parser.add_argument("minutes", nargs="*", type=int)
    args = parser.parse_args(argv)
    try:
        result = total_minutes(args.minutes)
    except ValueError as error:
        parser.error(str(error))
    print(result)
    return 0

if __name__ == "__main__":
    raise SystemExit(main())
Expected result
Run: python3 total.py 20 35
Output: 55
Run: python3 total.py --help
Output: generated usage and argument descriptions

Go deeper: [24] Python 3.11: argparse · [10] Python 3.11: modules

Keep these ideas

  • Modules expose reusable definitions; startup should be deliberate.
  • An environment isolates package sets, not untrusted code.
  • CLI parsing and presentation belong at the application edge.

Practise before moving on

Try each task before opening the solution. Explain your reasoning, including a boundary or failure case.

12.1 · Practice task

Why should importing a function from total.py not immediately print a report?

Hint: Import should make reusable behavior available without launching an application.

Read the worked solution

12.2 · Practice task

A package installs successfully but cannot be imported by your script. What two identities should you compare first?

Hint: Installation and execution may use different interpreters.

Read the worked solution

Chapter 13

Objects, dataclasses, and invariants

Use classes when they improve the domain model and keep rules close to state.

By the end of this chapter
  • Distinguish class and instance state
  • Validate a value object
  • Explain shallow immutability

When state needs a home

A class defines a type whose instances can keep related state and provide operations over it. Use an object when its identity, invariants or state transitions improve the model. Do not create a class merely because a file contains several functions; a straightforward function and dictionary may be enough for a small stateless transformation. The useful question is whether grouping the data and behavior makes invalid use harder to express.

The self parameter identifies the current instance in an ordinary method. Instance attributes belong to that object, while class attributes are looked up through the class and can accidentally become shared mutable state. A list placed on the class is not automatically a fresh list for every instance. Initialize per-instance mutable data inside the initializer, and test that changing one instance does not alter another.

Go deeper: [7] Python 3.11: classes and iterators

Invariants and data-oriented helpers

An invariant is a rule that every valid instance must preserve. A reading session may require a nonblank title and a nonnegative whole-number duration. Validate at creation and at every operation that can change the relevant state. Merely naming an attribute with a leading underscore communicates a convention; it does not create a security boundary against other Python code. Design APIs for cooperating programmers and validate external input before constructing domain objects.

A dataclass can generate common methods for a data-oriented object, reducing repetitive initializer and representation code. It does not infer your domain rules. A frozen dataclass prevents ordinary attribute assignment, but any mutable object referenced by one of its fields can still change. If you want values that are easy to reason about, combine constrained field types, immutable components and explicit validation rather than assuming one decorator guarantees deep immutability.

A small validated value object python
from dataclasses import dataclass

@dataclass(frozen=True)
class Session:
    title: str
    minutes: int

    def __post_init__(self):
        if not self.title.strip():
            raise ValueError("title must not be blank")
        if type(self.minutes) is not int or self.minutes < 0:
            raise ValueError("minutes must be a nonnegative integer")

session = Session("Python", 25)
print(session.title, session.minutes)
Expected result
Python 25

Go deeper: [16] Python 3.11: dataclasses · [7] Python 3.11: classes and iterators

Composition and a careful next step

Composition builds larger behavior by giving an object collaborators with narrower responsibilities. A report service can receive a record source rather than inheriting every possible file reader. This keeps I/O replaceable in tests. Inheritance is useful when one type genuinely satisfies another type's behavioral contract, but a family resemblance in names is not enough. If a subclass rejects inputs the parent promises to accept, callers can be surprised.

Keep this first model modest. Know how to construct an instance, inspect its state, call a method and explain which rules the method preserves. Then explore protocols, properties, inheritance and resource managers with specific problems. A class diagram is not a substitute for executable examples. Test that invalid construction fails clearly and that a successful operation cannot leave the object in a partially valid state.

Go deeper: [7] Python 3.11: classes and iterators · [16] Python 3.11: dataclasses

Keep these ideas

  • Objects are useful when they make state rules explicit.
  • A dataclass generates mechanics, not business validation.
  • Composition often makes dependencies easier to replace and test.

Practise before moving on

Try each task before opening the solution. Explain your reasoning, including a boundary or failure case.

13.1 · Practice task

Why can a class attribute notes = [] make two learner instances share notes?

Hint: The list is stored on the class unless each instance gets its own attribute.

Read the worked solution

13.2 · Practice task

Does frozen=True guarantee that a dataclass containing a list can never change? Explain.

Hint: Distinguish rebinding a field from mutating the object stored in it.

Read the worked solution

Chapter 14

Testing, type hints, and confidence

Build evidence around contracts rather than around implementation details.

By the end of this chapter
  • Write independent expectations
  • Separate unit and integration checks
  • Describe type-hint limits

Tests are executable claims

A test arranges inputs, performs an operation and compares the observed behavior with an expected result. It is strongest when the expectation comes from the contract or an independently worked example rather than a copy of the implementation. Testing the sum function by repeating the same buggy sum loop in the expected-value calculation can make both sides agree for the wrong reason. Use small values whose correct answer you can explain manually.

Cover normal cases, boundary cases and the specified failure cases. For an average calculation, useful examples include several observations, one observation, zero-valued observations and no observations. For a validator, assert the exception type and a useful aspect of its message where appropriate. Avoid tests that depend on the current clock, a personal folder or a remote service unless that dependency is the actual subject of the test.

Go deeper: [17] Python 3.11: unittest

Test boundaries without coupling internals

A unit test usually focuses on a small behavior with controlled dependencies. An integration test checks that cooperating pieces work together, such as parsing a temporary file and feeding the resulting records into a report. Both are useful, but they answer different questions. A thousand isolated tests cannot prove that a command-line argument reaches the intended calculation if no test exercises that connection.

Do not test private implementation details just because they are easy to inspect. A refactoring that preserves the public contract should not require rewriting every assertion. Make the observable behavior clear: returned values, deliberate state changes and reported failures. Temporary directories isolate file tests, and injected collaborators can avoid unnecessary real network calls. A test suite is also code, so keep its data and names readable.

Run with python 3 -m unittest test_average.py python · test_average.py
import unittest

def average(values):
    return None if not values else sum(values) / len(values)

class AverageTests(unittest.TestCase):
    def test_two_values(self):
        self.assertEqual(average([20, 40]), 30)

    def test_empty_is_missing(self):
        self.assertIsNone(average([]))

    def test_zero_is_observed(self):
        self.assertEqual(average([0]), 0)

if __name__ == "__main__":
    unittest.main()
Expected result
The runner reports3 passing tests. Timing and formatting depend on the Python version.

Go deeper: [17] Python 3.11: unittest · [6] Python 3.11: input and output

Type hints and feedback layers

Type annotations communicate intended shapes to readers and analysis tools. Ordinary Python does not enforce them automatically at runtime. A parameter annotated as int can still receive a string unless the caller or validation prevents it. Use annotations to clarify contracts and a static checker when the project benefits, while retaining runtime validation for external data. A successful type check and a successful test suite provide different kinds of evidence.

When a test fails, read the smallest relevant difference and repair the underlying behavior rather than loosening the assertion until it passes. Add a regression example for an actual defect, then consider the neighboring boundary. Passing tests do not prove a program has no defects; they show that the specified checked examples currently behave as expected. This honest limit helps you choose additional tests based on risk instead of chasing a decorative coverage number.

Different feedback catches different defectsSyntax checks, type analysis, tests and real observation provide complementary evidence. None alone establishes that every requirement is correct.Parse and importFind invalid syntax and import failuresStatic analysisInspect declared types and suspicious codeAutomated testsCheck selected behavior and boundariesReal useObserve the intended workflow and feedback
Different feedback catches different defects. Syntax checks, type analysis, tests and real observation provide complementary evidence. None alone establishes that every requirement is correct.Scroll horizontally to read the full diagram on a small screen.

Go deeper: [18] Python 3.11: type hints · [17] Python 3.11: unittest

Keep these ideas

  • Tests are selected executable examples of a contract.
  • Independent expected values avoid self-confirming mistakes.
  • Annotations, tests and runtime validation solve different problems.

Practise before moving on

Try each task before opening the solution. Explain your reasoning, including a boundary or failure case.

14.1 · Practice task

Why should a test for a three-record total use an independently calculated expected number?

Hint: The same faulty algorithm can agree with itself.

Read the worked solution

14.2 · Practice task

A function is annotated minutes: int. Can it safely trust a value decoded from an arbitrary JSON file?

Hint: Annotations do not validate external values at runtime.

Read the worked solution

Chapter 15

Algorithms, memory, and useful measurement

Improve the work being done before chasing tiny timing differences.

By the end of this chapter
  • Describe input-size growth
  • Benchmark a stated operation
  • Protect semantics during optimization

Count operations before measuring seconds

Performance starts with the amount of work. A loop that checks every existing item for each new item can perform roughly a quadratic number of comparisons. A set can often answer repeated membership questions with much less average lookup work, at the cost of additional memory and hashability requirements. This is a change in representation and algorithm, not merely a faster spelling of the same operation.

Keep an input-size model beside a performance claim. Sorting ten items and sorting ten million items are different workloads. State whether n means records, characters, files or distinct keys. Complexity describes growth under a model; it is not an exact stopwatch prediction. Disk access, interpreter overhead, caching and data distribution can dominate a small real task even when two algorithms share the same asymptotic class.

Go deeper: [4] Python 3.11: data structures · [19] Python 3.11: timeit

Measure a representative question

Once the correct behavior is clear, use a tool such as timeit for a small repeated operation or a profiler for a complete program. Construct inputs outside the timed expression when you want to measure lookup rather than setup. Keep the environment and workload description with the result, and repeat enough times to recognize noise. Do not publish a single timing from your laptop as a universal property of Python or of a library.

Measure memory as well as elapsed time when streaming or copying is involved. A generator can avoid retaining an intermediate list, while the consumer may still collect all results and use just as much final storage. A cache can speed repeated work but needs a limit and an invalidation policy. Optimization often moves cost from one part of the system to another, so explain both the benefit and the new obligation.

Compare work without claiming a universal timing python
known = {"python", "java", "sql"}
requests = ["python", "rust", "sql", "python"]
accepted = [topic for topic in requests if topic in known]
print(accepted)

# Optional local experiment; no fixed timing is promised.
# python3 -m timeit -s 's=set(range(10000))' '9999 in s'
# python3 -m timeit -s 's=list(range(10000))' '9999 in s'
Expected result
['python', 'sql', 'python']

Go deeper: [19] Python 3.11: timeit · [20] Python 3.11: tracemalloc

A practical stopping rule

Readable correct code is the baseline. Optimize a demonstrated bottleneck that matters to the intended user, then rerun behavioral tests to ensure the change did not alter the contract. A faster report that silently drops duplicate sessions is not an improvement if sessions are the unit being counted. Define acceptable latency or memory use before turning every function into a benchmarking project.

For a beginner's tool, bounded inputs, linear passes and sensible data structures usually provide enough headroom. Leave a clear path to larger-scale processing rather than prematurely adding threads, asynchronous I/O or a database. Those tools introduce new failure and coordination models. You will learn them more effectively when a measured workload gives you a concrete reason to investigate them.

Go deeper: [19] Python 3.11: timeit · [4] Python 3.11: data structures

Keep these ideas

  • Algorithmic choices often dominate syntactic tweaks.
  • A benchmark answers only its stated workload question.
  • A performance change must preserve the data contract.

Practise before moving on

Try each task before opening the solution. Explain your reasoning, including a boundary or failure case.

15.1 · Practice task

A duplicate checker scans all earlier items for every record. What alternative can reduce repeated lookup work, and what must remain explicit?

Hint: Use a structure built for membership.

Read the worked solution

15.2 · Practice task

Why is timing list creation plus lookup against lookup in an already-created set an unfair comparison?

Hint: The two measurements include different setup work.

Read the worked solution

Chapter 16

Capstone: a tested reading-ledger tool

Connect parsing, validation, calculation, errors and testing in one complete program.

By the end of this chapter
  • Run a complete command-line application
  • Explain its validation and output contract
  • Extend it without breaking established behavior

Specify the reading-ledger contract

Our capstone reads a JSON array of reading sessions and prints total minutes grouped by title. Each record must be an object with exactly title and minutes fields. Titles are trimmed, must remain nonblank and are grouped case-sensitively in this edition. Durations are nonnegative integers, with Booleans rejected explicitly. The program validates the complete input before printing a success report, so a bad later record cannot leave a partial report that looks complete.

This is a small local command-line tool, not a secure service for arbitrary-size uploads. The boundary below rejects files over one megabyte before parsing, and checks the byte count again after reading; a production service would add stronger streaming and filesystem threat assumptions. It also rejects nonstandard JSON constants and duplicate object fields to keep the accepted format predictable. A normal reading session with zero minutes is accepted; an empty dataset produces an explicit no-sessions message.

Go deeper: [13] Python 3.11: JSON · [24] Python 3.11: argparse

Separate adapters from a pure core

The loader handles paths, bytes, UTF-8 and JSON. The validator handles shape, allowed fields and domain values. The summarizer receives only accepted records and computes a new mapping without changing its input. The CLI chooses output and an exit code. These boundaries let a test check calculations without touching the filesystem, while a separate integration check verifies a real command and file.

Walk one example through the design before typing the full program. Two Python sessions of 25 and 35 minutes become one Python total of 60; a Java session of 20 remains a second key. Sorting the titles makes the output deterministic. A malformed minutes value in any row stops the report and names that row. We deliberately avoid silently guessing that the text "25" is numeric, because accepting two schema types complicates validation and can conceal an upstream mistake.

Reading-ledger architectureAll data is validated before the summarizer produces output. The pure core can be tested without a real file; failures at the input boundary result in a diagnostic and a nonzero exit status.CLIChoose file; expose help and statusLoaderBound bytes; decode UTF-8; parse JSONValidatorCheck shape, title and integer durationSummarizerGroup accepted records by exact titleReporterSort and display totals
Reading-ledger architecture. All data is validated before the summarizer produces output. The pure core can be tested without a real file; failures at the input boundary result in a diagnostic and a nonzero exit status.Scroll horizontally to read the full diagram on a small screen.

Go deeper: [13] Python 3.11: JSON · [5] Python 3.11: errors and exceptions

Complete implementation and verification plan

Save the implementation as ledger.py and the sample input as sessions.json. Run python 3 ledger.py sessions.json from the directory containing both files. For the shown sample, the report is Java:20 minutes, Python:60 minutes and Total:80 minutes on separate lines. The parser help explains the positional file argument. Expected input failures print an Error message to standard error and return status 2; unexpected programming defects are not disguised as a successful empty report.

The accompanying checks exercise the core's happy path, empty dataset, rejection of Boolean durations, a negative value and extra fields. Add an integration test using a temporary file, then run the actual CLI with malformed JSON and a missing path. Passing these cases is useful evidence, not a security audit or a claim that every filesystem race has been eliminated. Review the code yourself and extend the requirements deliberately before adding dates, persistence updates or a graphical interface.

The complete reading ledger python · ledger.py
import argparse
import json
import sys
from pathlib import Path

MAX_BYTES = 1_000_000

def reject_constant(value):
    raise ValueError("nonstandard JSON constant: " + value)

def unique_fields(pairs):
    result = {}
    for key, value in pairs:
        if key in result:
            raise ValueError("duplicate JSON field: " + key)
        result[key] = value
    return result

def validate_records(data):
    if not isinstance(data, list):
        raise ValueError("top level must be an array")
    records = []
    for row, item in enumerate(data, start=1):
        if not isinstance(item, dict) or set(item) != {"title", "minutes"}:
            raise ValueError(f"row {row}: expected title and minutes fields")
        title, minutes = item["title"], item["minutes"]
        if not isinstance(title, str) or not title.strip():
            raise ValueError(f"row {row}: title must be nonblank text")
        if type(minutes) is not int or minutes < 0:
            raise ValueError(f"row {row}: minutes must be a nonnegative integer")
        records.append({"title": title.strip(), "minutes": minutes})
    return records

def load_records(path):
    if path.stat().st_size > MAX_BYTES:
        raise ValueError("input exceeds the one-megabyte limit")
    raw = path.read_bytes()
    if len(raw) > MAX_BYTES:
        raise ValueError("input exceeds the one-megabyte limit")
    data = json.loads(raw.decode("utf-8"), parse_constant=reject_constant,
                      object_pairs_hook=unique_fields)
    return validate_records(data)

def summarize(records):
    totals = {}
    for record in records:
        title = record["title"]
        totals[title] = totals.get(title, 0) + record["minutes"]
    return totals

def main(argv=None):
    parser = argparse.ArgumentParser(description="Summarize a reading ledger")
    parser.add_argument("file", type=Path)
    args = parser.parse_args(argv)
    try:
        records = load_records(args.file)
    except (OSError, UnicodeError, ValueError) as error:
        print(f"Error: {error}", file=sys.stderr)
        return 2
    totals = summarize(records)
    if not records:
        print("No sessions.")
    for title in sorted(totals):
        print(f"{title}: {totals[title]} minutes")
    print(f"Total: {sum(totals.values())} minutes")
    return 0

if __name__ == "__main__":
    raise SystemExit(main())
Expected result
Java: 20 minutes
Python: 60 minutes
Total: 80 minutes
A small input fixture json · sessions.json
[
  {"title": "Python", "minutes": 25},
  {"title": "Java", "minutes": 20},
  {"title": "Python", "minutes": 35}
]
Core checks; run python 3 -m unittest test_ledger.py python · test_ledger.py
import unittest
from ledger import summarize, validate_records

class LedgerTests(unittest.TestCase):
    def test_grouping(self):
        rows = validate_records([
            {"title": "Python", "minutes": 25},
            {"title": " Python ", "minutes": 35}])
        self.assertEqual(summarize(rows), {"Python": 60})

    def test_empty(self):
        self.assertEqual(summarize(validate_records([])), {})

    def test_invalid_rows(self):
        for row in ({"title": "Python", "minutes": True},
                    {"title": "Python", "minutes": -1},
                    {"title": "Python", "minutes": 3, "extra": 1}):
            with self.subTest(row=row):
                with self.assertRaises(ValueError):
                    validate_records([row])

if __name__ == "__main__":
    unittest.main()
Expected result
The runner reports3 passing tests, including3 invalid-row subtests.

Go deeper: [17] Python 3.11: unittest · [15] Python 3.11: pathlib

Keep these ideas

  • A useful tool keeps parsing, validation, calculation and presentation separate.
  • Validate the entire required dataset before claiming a complete report.
  • New features need explicit contracts, boundaries and regression checks.

Practise before moving on

Try each task before opening the solution. Explain your reasoning, including a boundary or failure case.

16.1 · Practice task

Add a minimum-minutes command-line filter without hiding invalid source records. Specify when filtering happens and add two tests.

Hint: Validation must still inspect every input row before reporting success.

Read the worked solution

16.2 · Practice task

Design an export feature that writes totals to a chosen file without accidentally overwriting the source ledger.

Hint: The output is a new resource with its own failure and collision policy.

Read the worked solution

Practice with feedback

Worked solutions

These solutions show a valid line of reasoning. Compare assumptions and intermediate steps, rather than only the final number or output. Other implementations can be equally good when they preserve the stated contract.

Chapter 1 · Run, observe, and reason

Solution 1.1

The label remains Study minutes: and the number becomes 80. Multiplication is evaluated from the current input values, so changing the inputs is enough. If your output remains 75, first check whether you saved and launched the file you edited.

Return to the task

Solution 1.2

Check the current working directory, the exact filename and extension, and the path passed to Python. A file accidentally saved as hello.py.txt is a different file. Once the interpreter can locate the intended source, then investigate errors inside it.

Return to the task

Chapter 2 · Values, names, and numeric meaning

Solution 2.1

The output is 7 4. Initially both names identify the value four. The addition produces the value seven and rebinds a. Nothing in that assignment rebinds b, so it continues to refer to four.

Return to the task

Solution 2.2

Formatting can hide a fractional representation error while subsequent sums and comparisons still use the approximate values. Store integral cents for a fixed-cent domain or use Decimal values constructed from text, and specify which rounding rules apply to taxes, division and totals.

Return to the task

Chapter 3 · Strings, input, and honest conversion

Solution 3.1

Strings are immutable and strip returns a different string value. Assign the result with word = word.strip(), then print it. Avoid suggesting that all methods either mutate or return new objects; inspect the contract of the particular type.

Return to the task

Solution 3.2

Strip surrounding whitespace, reject the empty result, attempt int conversion in a narrow ValueError handler, then reject a negative result. Decide explicitly whether a leading plus sign is allowed. Do not use eval or delete arbitrary non-digit characters, since both expand or distort the accepted input.

Return to the task

Chapter 4 · Conditions and boundary thinking

Solution 4.1

For n = -5, the first condition is false but n <= 10 is true, so or accepts it. The inclusive range requires n >= 1 and n <= 10, or the chained comparison 1 <= n <= 10. Test the two boundaries and one value outside each side.

Return to the task

Solution 4.2

First check reading is None and report missing data. Otherwise, compare reading with zero or use it in the normal calculation. Using if not reading would send both states through the same path and could falsely report a real zero observation as absent.

Return to the task

Chapter 5 · Loops that you can prove will finish

Solution 5.1

Zero happens to work for nonempty positive inputs, but it invents a result for an empty list and fails for negative-only data if the function later expands. Prefer max with an explicit default policy, or initialize from the first value after checking that input exists.

Return to the task

Solution 5.2

Create accepted = [] and append each nonnegative value while looping over the original list. The original remains stable and the new list contains exactly the accepted values in order. Check [-1,-2,3], because adjacent rejected elements often reveal mutation-during-iteration bugs.

Return to the task

Chapter 6 · Functions, contracts, and scope

Solution 6.1

The first print happens inside the function. If the function reaches its end without return, Python returns None, which the caller then prints. Return the numeric total from the calculation and print it once at the outer boundary.

Return to the task

Solution 6.2

One policy is to return None for an empty collection and a float otherwise. A second policy could raise a documented ValueError. Both can work if callers and tests follow the same contract. Returning a fabricated zero without documenting that choice hides the difference between no observations and zero-valued observations.

Return to the task

Chapter 7 · Lists, tuples, copies, and ownership

Solution 7.1

sort mutates the existing list and deliberately returns None. To preserve values, use result = sorted(values), which creates a new list. Test the two variables after the operation rather than inferring behavior from the method name alone.

Return to the task

Solution 7.2

Assign a = [1] and b = a, append 2 through b, then print a. It contains [1,2] because both names identify the same list. Rebinding b = [9] afterward changes only b, so a remains [1,2]. That second step distinguishes mutation from rebinding.

Return to the task

Chapter 8 · Dictionaries, sets, and data questions

Solution 8.1

It counts distinct title values, not reading sessions. Repeated occurrences and original order are lost. Keep the original records or a mapping of counts if session frequency matters, and normalize titles only according to an explicit application rule.

Return to the task

Solution 8.2

Possible policies are reject duplicates, replace the previous record, or merge selected fields. A safe small import can reject duplicates with a line-numbered error, because silently choosing a winner can hide source mistakes. Test the chosen policy with adjacent and nonadjacent duplicates.

Return to the task

Chapter 9 · Comprehensions, iterators, and generators

Solution 9.1

sum requests values until exhaustion, so the iterator has no values left for the later list call. Create a new generator for the second traversal, or collect values once if repeated access justifies the memory. The correct choice depends on source repeatability and size.

Return to the task

Solution 9.2

Use a loop that validates each record, records or displays a warning through an explicit boundary, and appends a transformed value. A helper can own the pure transformation. This keeps the rejection policy and side effects visible and permits separate tests for each behavior.

Return to the task

Chapter 10 · Exceptions, tracebacks, and debugging

Solution 10.1

The user receives a success claim even when records were not imported, and the developer loses the original traceback needed to diagnose a defect. Catch known input or I/O failures at a boundary, return a failure status, and reserve success output for a completed verified operation.

Return to the task

Solution 10.2

Add a regression test specifying the empty-name behavior, then test a valid filename and a missing file separately. If empty input violates the public contract, reject it through ordinary validation rather than an assert that may be disabled.

Return to the task

Chapter 11 · Files, JSON, CSV, and data integrity

Solution 11.1

The JSON parser only recognizes the document structure and values. A separate domain validator must enforce minutes >= 0 and the expected field types. Treating parser success as proof of valid data allows syntactically correct but nonsensical records into calculations.

Return to the task

Solution 11.2

A naive split treats every comma as a separator and invents an extra column. csv.DictReader understands CSV quoting and maps the full quoted title to one field. Still test the dialect, header and conversion policy, because parser correctness does not decide the application schema.

Return to the task

Chapter 12 · Modules, environments, and command-line tools

Solution 12.1

Top-level code executes during import. Move report execution into main and call it only inside if __name__ == "__main__". Tests can then import total_minutes without parsing test-runner arguments or producing unrelated output.

Return to the task

Solution 12.2

Compare the interpreter used to run the script with the interpreter used to invoke pip, including any selected virtual environment. Prefer python -m pip with the intended interpreter. Also inspect whether a local file shadows the expected import name before reinstalling repeatedly.

Return to the task

Chapter 13 · Objects, dataclasses, and invariants

Solution 13.1

Attribute lookup can find the one list attached to the class. Mutating it affects what both instances observe. Assign self.notes = [] in the initializer to give each instance a distinct list, and test two instances together to detect accidental sharing.

Return to the task

Solution 13.2

No. Frozen behavior prevents normal reassignment of the field, but the referenced list may still accept append or item updates. Use immutable components such as tuples when that fits the contract, and describe the depth of immutability accurately.

Return to the task

Chapter 14 · Testing, type hints, and confidence

Solution 14.1

If the expected value repeats the production loop, the same mistake may occur in both places. Choose tiny records, calculate the total by hand and state that number in the test. Then add a different boundary case rather than duplicating the implementation.

Return to the task

Solution 14.2

No. The JSON record may contain text, null, a negative number or a Boolean, which Python treats as an int subclass. Validate the exact type and allowed range required by the domain before constructing accepted records. Static hints help cooperating code but do not replace input validation.

Return to the task

Chapter 15 · Algorithms, memory, and useful measurement

Solution 15.1

Maintain a set of seen stable identifiers and check membership before inserting each new identifier. This usually provides expected linear overall lookup work for ordinary hash-table assumptions. Preserve the duplicate rejection policy and remember that the set uses memory proportional to distinct stored identifiers.

Return to the task

Solution 15.2

One timing includes allocation and population while the other excludes it. Either include equivalent setup for a whole-workflow question or create both structures outside the timed region for a lookup-only question. Explain whether construction cost is paid once or on every real request.

Return to the task

Chapter 16 · Capstone: a tested reading-ledger tool

Solution 16.1

Parse the threshold as an integer, reject a negative threshold, load and validate all records, then filter accepted records before summarizing. Test a boundary session exactly at the threshold and a malformed row below the threshold; that row must still fail validation rather than being silently skipped.

Return to the task

Solution 16.2

Reject an output path that resolves to the same intended input location, decide whether existing destinations require an explicit overwrite flag, and write a complete temporary file before replacement. Add tests using temporary directories for an existing destination, a write failure and a Unicode title. Document that path comparison alone is not protection against a hostile filesystem race.

Return to the task

Retrieve before you review

Final knowledge check

Choose one answer for each question and write a short reason. Use the explanation to find the assumption or misconception behind an error.

  1. 1. Where does python 3 hello.py normally belong?

    1. Inside a quoted string
    2. In a system terminal
    3. After every print call
    4. Inside a list
    Check answer and reasoning
  2. 2. After a = 4; b = a; a = 7, what is b?

    1. 4
    2. 7
    3. None
    4. It raises an error
    Check answer and reasoning
  3. 3. What does input normally return?

    1. An integer when digits are typed
    2. A Boolean
    3. A string
    4. A parsed Python expression
    Check answer and reasoning
  4. 4. Which test distinguishes a missing reading from the valid value 0?

    1. if not reading
    2. if reading == False
    3. if reading
    4. if reading is None
    Check answer and reasoning
  5. 5. How many values does range(3) produce?

    1. 2
    2. 3
    3. 4
    4. An unbounded number
    Check answer and reasoning
  6. 6. A function reaches the end without return. What value does its caller receive?

    1. None
    2. 0
    3. The last printed text
    4. The last local variable
    Check answer and reasoning
  7. 7. What does a shallow copy separate?

    1. Every nested mutable object
    2. All identities in the graph
    3. The outer container only
    4. Nothing at all
    Check answer and reasoning
  8. 8. Which structure naturally counts occurrences by a stable topic key?

    1. A string alone
    2. A tuple index guess
    3. A Boolean
    4. A dictionary
    Check answer and reasoning
  9. 9. What happens after an ordinary generator is exhausted?

    1. It restarts automatically
    2. Further iteration produces no values
    3. It becomes a list
    4. It copies its source
    Check answer and reasoning
  10. 10. Which handler scope is usually safest for expected integer conversion failure?

    1. The conversion operation itself
    2. The entire application with every exception hidden
    3. Only unrelated logging
    4. No validation anywhere
    Check answer and reasoning
  11. 11. Valid JSON guarantees which property?

    1. Nonnegative application durations
    2. A trustworthy source
    3. Correct application field names
    4. Syntactic JSON structure and values
    Check answer and reasoning
  12. 12. What should importing a calculation module normally avoid?

    1. Defining functions
    2. Defining constants
    3. Prompting for interactive input
    4. Providing documentation
    Check answer and reasoning
  13. 13. A frozen dataclass contains a list. Which claim is accurate?

    1. The list is necessarily deeply immutable
    2. Normal field rebinding is blocked, but the list may still mutate
    3. All code becomes thread-safe
    4. The list is copied on every access
    Check answer and reasoning
  14. 14. Do type annotations automatically validate arbitrary JSON input?

    1. No; runtime boundary validation remains necessary
    2. Yes in every Python program
    3. Only if the file is large
    4. Only when using print
    Check answer and reasoning
  15. 15. Which benchmark comparison is fair for lookup-only cost?

    1. Include construction on just one side
    2. Use different data sizes
    3. Time a complete report against one lookup
    4. Prepare both structures outside the timed lookup
    Check answer and reasoning
  16. 16. Why validate all required records before printing a complete report?

    1. To make JSON syntax optional
    2. To hide later errors
    3. To avoid a partial result appearing complete
    4. To remove the need for tests
    Check answer and reasoning

Assessment explanations

1. Answer B

In a system terminal

The shell launches the interpreter. The interpreter then reads Python statements from the file.

Revisit the chapter · Return to the question

2. Answer A

4

Rebinding a does not rebind b. The assignment to b previously established its own reference.

Revisit the chapter · Return to the question

3. Answer C

A string

Input is text. Conversion and domain validation are separate deliberate operations.

Revisit the chapter · Return to the question

4. Answer D

if reading is None

None identifies the chosen missing-value state; truthiness would also treat zero as false.

Revisit the chapter · Return to the question

5. Answer B

3

The produced integers are 0,1 and 2 because the stop value is excluded.

Revisit the chapter · Return to the question

6. Answer A

None

An implicit return produces None; printing is a separate effect.

Revisit the chapter · Return to the question

7. Answer C

The outer container only

The new outer container retains references to the original nested elements.

Revisit the chapter · Return to the question

8. Answer D

A dictionary

A mapping can associate each normalized topic with its accumulated count.

Revisit the chapter · Return to the question

9. Answer B

Further iteration produces no values

Its traversal state is at the end. Create another generator or store results when repeated traversal is required.

Revisit the chapter · Return to the question

10. Answer A

The conversion operation itself

A narrow handler avoids misclassifying unrelated defects as bad numeric input.

Revisit the chapter · Return to the question

11. Answer D

Syntactic JSON structure and values

Parsing a format does not validate the application schema or domain rules.

Revisit the chapter · Return to the question

12. Answer C

Prompting for interactive input

Unexpected input on import makes reuse and tests dependent on an interactive environment.

Revisit the chapter · Return to the question

13. Answer B

Normal field rebinding is blocked, but the list may still mutate

Freezing attribute assignment does not recursively freeze referenced objects.

Revisit the chapter · Return to the question

14. Answer A

No; runtime boundary validation remains necessary

Annotations are not automatically enforced by ordinary runtime execution.

Revisit the chapter · Return to the question

15. Answer D

Prepare both structures outside the timed lookup

Equivalent setup makes the measurement match the stated lookup question.

Revisit the chapter · Return to the question

16. Answer C

To avoid a partial result appearing complete

A later invalid row should not leave earlier output presented as a complete successful import.

Revisit the chapter · Return to the question

Glossary

Alias
Another reference to the same object. Chapter
Argument
Value supplied to a function call. Chapter
Binding
Association between a name and an object. Chapter
CLI
Command-line interface accepting arguments and returning output and status. Chapter
Complexity
Model describing resource growth with input size. Chapter
Context manager
Object implementing a setup/cleanup protocol used by with. Chapter
Dataclass
Class helper generating selected common methods from declared fields. Chapter
Domain validation
Checking values against application meaning and allowed states. Chapter
Expression
Code evaluated to produce a value. Chapter
Generator
An iterator produced by a generator function or expression. Chapter
Hashable
Usable under a stable equality/hash contract as a mapping key or set element. Chapter
Identity
Which particular object a reference identifies. Chapter
Immutable
Not permitting changes to the object’s value through its normal operations. Chapter
Interpreter
Program that executes Python source semantics. Chapter
Invariant
A rule maintained across an operation or repeated step. Chapter
Iterable
Object that can provide an iterator. Chapter
Iterator
Stateful provider of successive values until exhaustion. Chapter
Module
A unit of Python code with its own namespace. Chapter
Mutable
Able to change an object’s state after creation. Chapter
Parameter
Local input name declared by a function. Chapter
Regression test
Check preserving the expected behavior of a previously failing case. Chapter
Return value
Result passed back from a function to its caller. Chapter
Schema
Rules for a structured document’s accepted shape and field types. Chapter
Shallow copy
New outer container retaining references to existing nested elements. Chapter
Short-circuit
Skipping a later Boolean operand when an earlier one determines the result. Chapter
Slice
A selected sequence range with an excluded stop. Chapter
Source file
Saved text containing program instructions. Chapter
Traceback
Reported chain of calls leading to an exception. Chapter
Truthiness
How a value is interpreted in a Boolean context. Chapter
Type annotation
Declared type information for readers and analysis tools. Chapter
Unicode
A standard for representing text using defined code points. Chapter
Virtual environment
Project-specific package environment based on a Python installation. Chapter

Read and watch with a purpose

Reading and video library

Use the chapter source links to choose a relevant next explanation. Each entry below states what it adds. Documentation links may evolve; edition 2026.12 records the assumptions used here.

  1. The Python 3.11 tutorial

    Python Software Foundation · docs

    Language overview and further structured study.

    https://docs.python.org/3.11/tutorial/
  2. Python 3.11: informal introduction

    Python Software Foundation · docs

    Numbers, strings, lists and basic execution.

    https://docs.python.org/3.11/tutorial/introduction.html
  3. Python 3.11: control flow and functions

    Python Software Foundation · docs

    Branches, iteration, calls and default arguments.

    https://docs.python.org/3.11/tutorial/controlflow.html
  4. Python 3.11: data structures

    Python Software Foundation · docs

    Lists, dictionaries, sets and comprehensions.

    https://docs.python.org/3.11/tutorial/datastructures.html
  5. Python 3.11: errors and exceptions

    Python Software Foundation · docs

    Exception handling, propagation and cleanup.

    https://docs.python.org/3.11/tutorial/errors.html
  6. Python 3.11: input and output

    Python Software Foundation · docs

    Text files, formatting and resource management.

    https://docs.python.org/3.11/tutorial/inputoutput.html
  7. Python 3.11: classes and iterators

    Python Software Foundation · docs

    Objects, namespaces, sharing and iteration.

    https://docs.python.org/3.11/tutorial/classes.html
  8. Python 3.11: built-in types

    Python Software Foundation · docs

    Precise sequence, mapping, numeric and text behavior.

    https://docs.python.org/3.11/library/stdtypes.html
  9. Python 3.11: built-in functions

    Python Software Foundation · docs

    Contracts for conversion, iteration and inspection.

    https://docs.python.org/3.11/library/functions.html
  10. Python 3.11: modules

    Python Software Foundation · docs

    Imports, namespaces and application entry points.

    https://docs.python.org/3.11/tutorial/modules.html
  11. Python 3.11: virtual environments

    Python Software Foundation · docs

    Environment creation and limitations.

    https://docs.python.org/3.11/library/venv.html
  12. Python Packaging User Guide

    Python Packaging Authority · docs

    Further package installation guidance; rolling documentation.

    https://packaging.python.org/en/latest/tutorials/installing-packages/
  13. Python 3.11: JSON

    Python Software Foundation · docs

    Parsing behavior, hooks and untrusted-data caveats.

    https://docs.python.org/3.11/library/json.html
  14. Python 3.11: CSV

    Python Software Foundation · docs

    Quoting, dialects and newline handling.

    https://docs.python.org/3.11/library/csv.html
  15. Python 3.11: pathlib

    Python Software Foundation · docs

    Portable path descriptions and filesystem operations.

    https://docs.python.org/3.11/library/pathlib.html
  16. Python 3.11: dataclasses

    Python Software Foundation · docs

    Generated methods, field defaults and frozen semantics.

    https://docs.python.org/3.11/library/dataclasses.html
  17. Python 3.11: unittest

    Python Software Foundation · docs

    Test cases, fixtures, discovery and assertions.

    https://docs.python.org/3.11/library/unittest.html
  18. Python 3.11: type hints

    Python Software Foundation · docs

    Annotation meaning and runtime limits.

    https://docs.python.org/3.11/library/typing.html
  19. Python 3.11: timeit

    Python Software Foundation · docs

    Microbenchmarking with explicit setup.

    https://docs.python.org/3.11/library/timeit.html
  20. Python 3.11: tracemalloc

    Python Software Foundation · docs

    Investigating tracked Python memory allocations.

    https://docs.python.org/3.11/library/tracemalloc.html
  21. Python 3.11: decimal arithmetic

    Python Software Foundation · docs

    Decimal representation and explicit rounding contexts.

    https://docs.python.org/3.11/library/decimal.html
  22. CS 50 Introduction to Programming with Python: free video lectures

    Harvard OpenCourseWare · Watch / course

    Optional explanatory lectures, demonstrations and course exercises; certificates have separate terms.

    https://cs50.harvard.edu/python/
  23. Continue in the OpenLearning Python library

    OpenLearning · docs

    Read chapters, practise questions and contribute corrections on the platform.

    https://ankit-kotnala.github.io/OpenLearning/courses/python/
  24. Python 3.11: argparse

    Python Software Foundation · docs

    Command-line parsing, generated help and argument error behavior.

    https://docs.python.org/3.11/library/argparse.html

Continue on OpenLearning

Use the subject library to move between reading, practice, study material, and the wider topic map.

Make the explanation better

If a paragraph needs a clearer example, a command changes, or a diagram hides an important assumption, propose a correction in the open-source repository. Explain the issue and add a source or a reproducible example.

Editable book sources on GitHub

Original OpenLearning instructional text and diagrams: CC BY-SA 4.0. Original code: MIT. External material retains its own copyright and license. This book links to authorized resources; it does not relicense them.