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
Clear explanations. Worked examples. Practice with reasoning. Original text · CC BY-SA 4.0 Code · MIT
Before you begin
How to use this guide
Learners new to programming and developers who want a careful foundation before frameworks.
Helpful background
Comfort creating a folder and saving a text file
A computer with Python 3.11 or newer for following the edition target
No previous programming language is required
What you will be able to do
Trace names, objects, branches, loops and function calls
Choose collections and explain mutation, aliasing and shallow copies
Read and validate structured files without hiding failures
Organize modules and write focused automated tests
Build a complete command-line reading ledger with validation and useful error messages
Recognize where this foundation ends and select the next topic deliberately
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
Examples target Python 3.11+ core syntax and standard-library APIs. They avoid newer release-only features. The available execution runtime for this authoring pass was CPython 3.9.6, so execution checks do not constitute a Python 3.11 platform certification.
This book develops practical foundations; asynchronous servers, numerical computing, web frameworks, packaging for public distribution, descriptors and metaclasses require further study.
All teaching prose, exercises, diagrams and examples are original. References and optional course videos remain at their authorized hosts.
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.
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
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 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.
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.
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)
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 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.
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.
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
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 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.
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.
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))
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.
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 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.
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)
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.
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 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.
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([]))
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.
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.
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
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.
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.
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))
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 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.
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.
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 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.
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.
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])
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.
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)
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.
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.
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)
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 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.
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 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.
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.
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())
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.
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)
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.
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.
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.
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 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.
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.
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'
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.
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.
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 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.
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())
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.