Python Basics
This chapter builds the exact execution model needed before frameworks: values and names, branching and iteration, reusable functions, compact collection transforms, and safe text formatting.
- Explain Variables & data types by naming its input, guarantee, internal lifecycle, important failure, and proof.
- Explain Control flow by naming its input, guarantee, internal lifecycle, important failure, and proof.
- Explain Functions & scope by naming its input, guarantee, internal lifecycle, important failure, and proof.
- Explain Comprehensions by naming its input, guarantee, internal lifecycle, important failure, and proof.
- Explain String formatting by naming its input, guarantee, internal lifecycle, important failure, and proof.
How to use this chapter
For Python Basics, read the explanations first and predict every example before running it. Keep a learning repository containing code, tests, command output, and the short written submission. The roadmap checklist at the end audits coverage; the chapter itself follows the language learning arc appropriate to this subject.
The problem this chapter solves
This chapter builds the exact execution model needed before frameworks: values and names, branching and iteration, reusable functions, compact collection transforms, and safe text formatting.
The language lets a team express business rules quickly while retaining escape hatches for typing, concurrency, native extensions, packaging, and performance profiling.
Learning outcomes
- Explain Variables & data types by naming its input, guarantee, internal lifecycle, important failure, and proof.
- Explain Control flow by naming its input, guarantee, internal lifecycle, important failure, and proof.
- Explain Functions & scope by naming its input, guarantee, internal lifecycle, important failure, and proof.
- Explain Comprehensions by naming its input, guarantee, internal lifecycle, important failure, and proof.
- Explain String formatting by naming its input, guarantee, internal lifecycle, important failure, and proof.
- Explain Complete string method reference by naming its input, guarantee, internal lifecycle, important failure, and proof.
- Trace the chapter's complete execution path and identify where memory, I/O, concurrency, persistence, or rendering cost accumulates.
- Build the worked example, make one failure visible, and defend the design in a review.
Chapter progression
The order below is intentional: later sections depend on guarantees established earlier.
Runtime or system overview
CPython compiles a module to bytecode, executes frames on a virtual machine, stores ordinary objects on a managed heap, and primarily reclaims them through reference counting with a cyclic garbage collector as a backstop. Names point to objects; assignment does not copy an object. The Global Interpreter Lock protects interpreter state in the standard CPython build, so threads are excellent for much I/O but not a general CPU-parallelism mechanism. In Python Basics, use that execution model to decide where the chapter's validation, state ownership, cleanup, and evidence belong.
Execution trace
- Python executes the module top to bottom, creating imported names, constants, classes, and function objects before the example call runs.
- The call creates a frame, binds arguments to local names, and validates or normalizes each boundary value before deriving the result.
- Expressions evaluate left to right subject to Python's short-circuit rules; container operations allocate objects and retain references described in the memory section.
- A deliberate exception immediately begins stack unwinding; otherwise
returnpasses the result reference to the caller and the frame becomes collectible when no suspended work retains it. - The final print or assertion exposes the observable value, and edge-case tests repeat the same trace with empty, invalid, duplicate, or worst-shape input.
Memory and performance lens
A local name lives in a frame's fast-locals storage, while the referenced object normally lives on the heap. Immutable objects may be shared or interned. Containers store references, not embedded copies. Generators and coroutines preserve suspended frames, so retained locals stay alive until completion or close(). For Python Basics, connect those costs to the concrete operations in the topic sections rather than assuming the friendly surface syntax is cheap.
When tuning Python Basics, measure allocation count, retained-object size, iterator materialization, CPU profile, file/network call count, and execution time on representative input rather than optimizing from source-code appearance.
1. Variables & data types
The Variables & data types unit begins with int/float/str/bool/None: Python's core scalar values include arbitrary-precision integers, binary64 floating-point numbers, immutable Unicode strings, booleans, and the singleton None. Choose the type that models the domain and use decimal.Decimal for exact base-10 money rather than binary float. The rest of this section connects that guarantee to this unit's related roadmap concepts instead of treating each term as an isolated flashcard.
The language model: Variables & data types
| Concept | Meaning | Engineering decision |
|---|---|---|
| int/float/str/bool/None | Python's core scalar values include arbitrary-precision integers, binary64 floating-point numbers, immutable Unicode strings, booleans, and the singleton None. | Choose the type that models the domain and use decimal.Decimal for exact base-10 money rather than binary float. |
| type conversion: int()/str()/float() | Conversion constructs a value in a target type from an accepted representation. | Validate boundaries and keep the typed value after conversion. |
| id() and is vs == | == asks whether values are equivalent; is asks whether two references designate the same object. | Use is for singletons such as None; use == for domain values. |
| constants convention | Python has no enforced constant keyword; module-level UPPER_SNAKE_CASE communicates that a binding should not be reassigned. | Use constants for stable configuration-independent values and enums for a closed domain vocabulary. |
What the runtime actually does: Variables & data types
int/float/str/bool/None. Every value is an object with a type and identity. bool is a subclass of int; float follows IEEE-754 behavior such as rounding and NaN; str stores Unicode and creates a new string for transformations; None represents absence, not zero or an empty string.
type conversion: int()/str()/float(). The target type parses or adapts the input and raises ValueError or TypeError when the contract is violated.
id() and is vs ==. Python dispatches equality through __eq__; identity is a direct object-identity check. Small-object caching can make a mistaken identity comparison appear to work.
constants convention. The runtime treats a so-called constant like any other name. Type checkers can additionally use Final, but object mutability remains separate from name reassignment.
Read these as one system: int/float/str/bool/None establishes the starting contract, type conversion: int()/str()/float() changes how that contract is executed or represented, and constants convention exposes a later boundary or failure condition. A local optimization is useful only when the combined behavior stays correct and observable.
Read the syntax in context: Variables & data types
1count: int = 422ratio: float = 0.753name: str = "Dev"4active: bool = True5missing: None = NoneThis Variables & data types slice makes int/float/str/bool/None observable. Read it from the boundary inward: identify the input, the validation point, the state or operation, and the value that proves the result. Before extending it toward constants convention, predict its behavior for empty, invalid, repeated, and large input.
Mistakes that change program meaning: Variables & data types
| Risk | Why it matters |
|---|---|
| int/float/str/bool/None | Truthiness can collapse distinct states: 0, '', empty containers, and None are all falsey but do not mean the same thing. |
| type conversion: int()/str()/float() | Do not catch every exception or silently coerce malformed user data. |
| id() and is vs == | Never rely on string or integer interning. |
| constants convention | An uppercase name pointing to a mutable list can still be mutated; convention is not immutability. |
Code it, observe it, explain it: Variables & data types
- Foundation: implement or demonstrate int/float/str/bool/None with one valid input and one invalid input. Record the exact output or failure.
- Integration: combine int/float/str/bool/None with type conversion: int()/str()/float(). Explain which component owns validation and cleanup.
- Production: design a test or experiment that exposes the failure described for constants convention. State the metric, assertion, or query plan that proves the correction.
What a strong checkpoint answer contains
- A precise boundary and typed or validated input.
- One named guarantee, not only a library call.
- A negative case that fails for the intended reason.
- Cleanup, transaction, retry, or cancellation behavior where applicable.
- Evidence: assertion, command output, plan, trace, metric, or accessible UI state.
2. Control flow
The Control flow unit begins with if/elif/else + nested conditions: Conditional statements execute exactly one matching branch in source order, with an optional fallback branch. Use early returns and named predicates to keep business rules flat and auditable. The rest of this section connects that guarantee to this unit's related roadmap concepts instead of treating each term as an isolated flashcard.
The language model: Control flow
| Concept | Meaning | Engineering decision |
|---|---|---|
| if/elif/else + nested conditions | Conditional statements execute exactly one matching branch in source order, with an optional fallback branch. | Use early returns and named predicates to keep business rules flat and auditable. |
| for: range()/enumerate()/zip() | A for loop consumes an iterable through the iterator protocol; range lazily describes integers, enumerate pairs items with counters, and zip advances iterables in parallel. | Use enumerate instead of manual counters and zip(..., strict=True) when unequal lengths are a data error. |
| while + break/continue/else | A while loop repeats while its condition is truthy; break exits, continue begins the next check, and loop else runs only when the loop ends without break. | Use it when the number of iterations depends on evolving state, and make the progress/termination invariant explicit. |
| ternary expressions | A conditional expression chooses one of two values: value_if_true if condition else value_if_false. | Use it for one short value choice; use a statement for multi-step logic. |
| match/case (Python 3.10+) | Structural pattern matching selects a case by the shape and values of an object and can bind parts of that structure to names. | Use it for tagged records, protocol messages, and algebraic-style variants where structure is clearer than repeated indexing. |
What the runtime actually does: Control flow
if/elif/else + nested conditions. CPython evaluates each condition and applies truth-value testing (__bool__, then __len__ where applicable). Short-circuit and and or stop as soon as the result is known and return an operand, not necessarily a boolean.
for: range()/enumerate()/zip(). for calls iter() once and next() until StopIteration. range stores start/stop/step rather than all numbers. zip stops at the shortest iterable unless strict checking is enabled.
while + break/continue/else. The condition is reevaluated before every iteration. finally cleanup still runs when break or continue transfers control.
ternary expressions. Only the selected value expression is evaluated, so side effects in the other branch do not run.
match/case (Python 3.10+). Patterns are tried top to bottom; captures bind names, guards run only after a structural match, and an unqualified name is usually a capture rather than a value constant.
Read these as one system: if/elif/else + nested conditions establishes the starting contract, for: range()/enumerate()/zip() changes how that contract is executed or represented, and match/case (Python 3.10+) exposes a later boundary or failure condition. A local optimization is useful only when the combined behavior stays correct and observable.
Read the syntax in context: Control flow
1if condition:2 ...3elif other:4 ...5else:6 ...This Control flow slice makes if/elif/else + nested conditions observable. Read it from the boundary inward: identify the input, the validation point, the state or operation, and the value that proves the result. Before extending it toward match/case (Python 3.10+), predict its behavior for empty, invalid, repeated, and large input.
Mistakes that change program meaning: Control flow
| Risk | Why it matters |
|---|---|
| if/elif/else + nested conditions | Deep nesting and mixed and/or expressions without parentheses hide precedence and missed cases. |
| for: range()/enumerate()/zip() | Mutating a collection's size during iteration or assuming ordinary zip validates equal lengths causes skipped work or silent truncation. |
| while + break/continue/else | Forgetting to update the state that controls the condition creates an infinite loop. |
| ternary expressions | Nested conditional expressions are difficult to read and associate from the right. |
| match/case (Python 3.10+) | Writing case STATUS_OK: usually captures anything unless it is a qualified constant; use enums or qualified names. |
Code it, observe it, explain it: Control flow
- Foundation: implement or demonstrate if/elif/else + nested conditions with one valid input and one invalid input. Record the exact output or failure.
- Integration: combine if/elif/else + nested conditions with for: range()/enumerate()/zip(). Explain which component owns validation and cleanup.
- Production: design a test or experiment that exposes the failure described for match/case (Python 3.10+). State the metric, assertion, or query plan that proves the correction.
What a strong checkpoint answer contains
- A precise boundary and typed or validated input.
- One named guarantee, not only a library call.
- A negative case that fails for the intended reason.
- Cleanup, transaction, retry, or cancellation behavior where applicable.
- Evidence: assertion, command output, plan, trace, metric, or accessible UI state.
3. Functions & scope
The Functions & scope unit begins with *def/return/default args/args/kwargs: A function packages a call contract with positional, keyword, variadic, defaulted, and return behavior. Use keyword-only options for clarity and None plus initialization inside the function for mutable defaults. The rest of this section connects that guarantee to this unit's related roadmap concepts instead of treating each term as an isolated flashcard.
The language model: Functions & scope
| Concept | Meaning | Engineering decision |
|---|---|---|
| *def/return/default args/args/kwargs | A function packages a call contract with positional, keyword, variadic, defaulted, and return behavior. | Use keyword-only options for clarity and None plus initialization inside the function for mutable defaults. |
| LEGB scope rule | Name lookup proceeds through Local, Enclosing, Global, then Builtins scopes. | Use parameters and returns for most data flow; reserve nonlocal for a deliberate closure state. |
| lambda functions | A lambda creates a small anonymous function containing one expression. | Use it for a short key, predicate, or adapter passed directly to another function. |
| closures | A closure is a function that retains bindings from an enclosing lexical scope after that outer call returns. | Use closures for configured callbacks and small stateful factories. |
What the runtime actually does: Functions & scope
*def/return/default args/args/kwargs. A function object is created when def executes. Default expressions are evaluated once at definition time. Each call creates a frame, binds arguments, and returns None when execution reaches the end without return.
LEGB scope rule. A function's compiled symbol table determines whether an identifier is local, free, global, or built-in; assignment makes a name local unless global or nonlocal says otherwise.
lambda functions. It follows ordinary lexical scope and late binding; the expression is evaluated when called, not when the lambda is created.
closures. The captured values live in cells referenced by the inner function; they remain reachable as long as the closure remains reachable.
Read these as one system: *def/return/default args/args/kwargs establishes the starting contract, LEGB scope rule changes how that contract is executed or represented, and closures exposes a later boundary or failure condition. A local optimization is useful only when the combined behavior stays correct and observable.
Read the syntax in context: Functions & scope
1def call(required, *args, option=True, **kwargs): ...This Functions & scope slice makes *def/return/default args/args/kwargs observable. Read it from the boundary inward: identify the input, the validation point, the state or operation, and the value that proves the result. Before extending it toward closures, predict its behavior for empty, invalid, repeated, and large input.
Mistakes that change program meaning: Functions & scope
| Risk | Why it matters |
|---|---|
| def/return/default args/args/*kwargs | A mutable default such as items=[] is shared by every call and accumulates state. |
| LEGB scope rule | Reading a local before its assignment raises UnboundLocalError, even if a global has the same name. |
| lambda functions | Complex lambdas hide control flow and have less useful tracebacks; use def when naming improves meaning. |
| closures | Late binding in loops captures the variable, not its historical value; bind a default argument when needed. |
Code it, observe it, explain it: Functions & scope
- Foundation: implement or demonstrate *def/return/default args/args/kwargs with one valid input and one invalid input. Record the exact output or failure.
- Integration: combine *def/return/default args/args/kwargs with LEGB scope rule. Explain which component owns validation and cleanup.
- Production: design a test or experiment that exposes the failure described for closures. State the metric, assertion, or query plan that proves the correction.
What a strong checkpoint answer contains
- A precise boundary and typed or validated input.
- One named guarantee, not only a library call.
- A negative case that fails for the intended reason.
- Cleanup, transaction, retry, or cancellation behavior where applicable.
- Evidence: assertion, command output, plan, trace, metric, or accessible UI state.
4. Comprehensions
The Comprehensions unit begins with list comp vs for loop: A list comprehension maps and optionally filters an iterable into a newly allocated list. Use it for one clear transformation/filter and a generator expression for lazy consumption. The rest of this section connects that guarantee to this unit's related roadmap concepts instead of treating each term as an isolated flashcard.
The language model: Comprehensions
| Concept | Meaning | Engineering decision |
|---|---|---|
| list comp vs for loop | A list comprehension maps and optionally filters an iterable into a newly allocated list. | Use it for one clear transformation/filter and a generator expression for lazy consumption. |
| dict comp + filtering | A dictionary comprehension constructs key/value pairs, optionally including only elements that satisfy a condition. | Use it to index items by a stable unique key or transform an existing mapping. |
| set comp for deduplication | A set comprehension constructs unique hashable values and discards duplicate occurrences. | Use it for membership, algebra, and deduplication when original order is irrelevant. |
| nested comprehensions | A nested comprehension expresses a nested iteration and can flatten or build matrix-like data. | Use at most a small, readable nesting and spell out loops when indexes or conditions are nontrivial. |
What the runtime actually does: Comprehensions
list comp vs for loop. Its loop variable has comprehension-local scope in Python 3. The whole result list is retained; evaluation is eager and ordered.
dict comp + filtering. Keys are hashed as inserted. A later duplicate key overwrites the earlier value while retaining the key's insertion position.
set comp for deduplication. Membership uses hashes followed by equality checks; ordinary sets do not promise a semantic ordering contract.
nested comprehensions. for clauses are evaluated left to right, matching nested loops in that order; every output element is allocated eagerly for a list comprehension.
Read these as one system: list comp vs for loop establishes the starting contract, dict comp + filtering changes how that contract is executed or represented, and nested comprehensions exposes a later boundary or failure condition. A local optimization is useful only when the combined behavior stays correct and observable.
Read the syntax in context: Comprehensions
1[transform(x) for x in items if predicate(x)]This Comprehensions slice makes list comp vs for loop observable. Read it from the boundary inward: identify the input, the validation point, the state or operation, and the value that proves the result. Before extending it toward nested comprehensions, predict its behavior for empty, invalid, repeated, and large input.
Mistakes that change program meaning: Comprehensions
| Risk | Why it matters |
|---|---|
| list comp vs for loop | Side effects, nested conditions, or expensive repeated expressions make a comprehension harder to understand than a loop. |
| dict comp + filtering | Silent duplicate-key overwrite can lose data; detect duplicates when uniqueness is an invariant. |
| set comp for deduplication | Using mutable/unhashable elements fails, and using a set when order matters produces unstable output. |
| nested comprehensions | Reversing clause order changes both binding availability and output order. |
Code it, observe it, explain it: Comprehensions
- Foundation: implement or demonstrate list comp vs for loop with one valid input and one invalid input. Record the exact output or failure.
- Integration: combine list comp vs for loop with dict comp + filtering. Explain which component owns validation and cleanup.
- Production: design a test or experiment that exposes the failure described for nested comprehensions. State the metric, assertion, or query plan that proves the correction.
What a strong checkpoint answer contains
- A precise boundary and typed or validated input.
- One named guarantee, not only a library call.
- A negative case that fails for the intended reason.
- Cleanup, transaction, retry, or cancellation behavior where applicable.
- Evidence: assertion, command output, plan, trace, metric, or accessible UI state.
5. String formatting
The String formatting unit begins with f-strings + format specifiers: An f-string evaluates embedded Python expressions and formats their values using each type's __format__ protocol. Use f-strings for developer-controlled templates and explicit specifiers for stable presentation. The rest of this section connects that guarantee to this unit's related roadmap concepts instead of treating each term as an isolated flashcard.
The language model: String formatting
| Concept | Meaning | Engineering decision |
|---|---|---|
| f-strings + format specifiers | An f-string evaluates embedded Python expressions and formats their values using each type's __format__ protocol. | Use f-strings for developer-controlled templates and explicit specifiers for stable presentation. |
| format() method | str.format replaces numbered or named fields in a developer-controlled template using the same format-spec mini-language as f-strings. | Use it when the template must be stored independently but is still trusted application content. |
| Template strings | string.Template performs deliberately simple $name substitution. | Use it for simple user-editable templates where full expression formatting is undesirable. |
| strip/split/join/replace/find | Python string methods create or locate text without mutating the original immutable string. | Normalize at boundaries and prefer separator join over repeated concatenation in a loop. |
What the runtime actually does: String formatting
f-strings + format specifiers. The compiler builds formatting bytecode; width, alignment, precision, numeric grouping, and datetime specifiers are delegated to the value type.
format() method. Field lookup and __format__ occur at runtime, which allows a template to be chosen separately from its values.
Template strings. substitute raises for missing names, while safe_substitute leaves unresolved placeholders. It does not evaluate Python expressions.
strip/split/join/replace/find. strip removes a set of edge characters (or whitespace), split tokenizes, join performs one efficient concatenation pass, replace creates a new value, and find returns -1 when absent.
Read these as one system: f-strings + format specifiers establishes the starting contract, format() method changes how that contract is executed or represented, and strip/split/join/replace/find exposes a later boundary or failure condition. A local optimization is useful only when the combined behavior stays correct and observable.
Read the syntax in context: String formatting
1f"{amount:,.2f} | {created_at:%Y-%m-%d}"This String formatting slice makes f-strings + format specifiers observable. Read it from the boundary inward: identify the input, the validation point, the state or operation, and the value that proves the result. Before extending it toward strip/split/join/replace/find, predict its behavior for empty, invalid, repeated, and large input.
Mistakes that change program meaning: String formatting
| Risk | Why it matters |
|---|---|
| f-strings + format specifiers | Formatting is presentation, not localization or SQL/shell escaping; never treat it as an injection defense. |
| format() method | Do not accept arbitrary format strings from untrusted users because attribute/index traversal can expose data. |
| Template strings | safe_substitute can hide a missing required value; validate required placeholders explicitly. |
| strip/split/join/replace/find | strip('.txt') removes any of those characters from both ends; use removesuffix('.txt') for an exact suffix. |
Code it, observe it, explain it: String formatting
- Foundation: implement or demonstrate f-strings + format specifiers with one valid input and one invalid input. Record the exact output or failure.
- Integration: combine f-strings + format specifiers with format() method. Explain which component owns validation and cleanup.
- Production: design a test or experiment that exposes the failure described for strip/split/join/replace/find. State the metric, assertion, or query plan that proves the correction.
What a strong checkpoint answer contains
- A precise boundary and typed or validated input.
- One named guarantee, not only a library call.
- A negative case that fails for the intended reason.
- Cleanup, transaction, retry, or cancellation behavior where applicable.
- Evidence: assertion, command output, plan, trace, metric, or accessible UI state.
6. Complete string method reference
The Complete string method reference unit begins with case conversion: lower/upper/casefold/title/capitalize/swapcase: Case-conversion methods return new Unicode strings; casefold is the aggressive normalization intended for caseless comparison, while lower/upper/title/capitalize are presentation transformations. Use casefold()—often with Unicode normalization—for caseless identifiers only when the domain permits it; preserve the original for display. The rest of this section connects that guarantee to this unit's related roadmap concepts instead of treating each term as an isolated flashcard.
The language model: Complete string method reference
| Concept | Meaning | Engineering decision |
|---|---|---|
| case conversion: lower/upper/casefold/title/capitalize/swapcase | Case-conversion methods return new Unicode strings; casefold is the aggressive normalization intended for caseless comparison, while lower/upper/title/capitalize are presentation transformations. | Use casefold()—often with Unicode normalization—for caseless identifiers only when the domain permits it; preserve the original for display. |
| prefix and suffix: startswith/endswith/removeprefix/removesuffix | Prefix/suffix methods test or remove an exact substring without treating it as a set of characters. | Use them instead of manual slicing or strip when parsing a simple, already-defined marker. |
| search and count: index/rindex/rfind/count | Search methods locate substrings in forward or reverse direction; find returns -1, index raises ValueError, and count counts non-overlapping matches. | Use in for existence, find when the sentinel is convenient, and index when absence is exceptional. |
| partitioning: partition/rpartition/splitlines | partition splits once into (before, separator, after) without raising when absent; rpartition starts from the right; splitlines recognizes several Unicode line boundaries. | Use partition for one unambiguous delimiter and splitlines for logical text records. |
| character tests: isalpha/isdigit/isdecimal/isnumeric/isalnum/isspace/isidentifier | Character-test methods apply Unicode character properties to a non-empty string; decimal, digit, and numeric recognize increasingly broad sets. | Use isdecimal for conservative decimal-digit input and combine isidentifier with keyword.iskeyword when validating Python identifiers. |
| translation and encoding: maketrans/translate/encode | translate maps or deletes Unicode code points using a translation table; encode converts Unicode text to bytes using a named codec and error policy. | Keep text as str internally and encode/decode only at I/O boundaries with an explicit codec, normally UTF-8. |
What the runtime actually does: Complete string method reference
case conversion: lower/upper/casefold/title/capitalize/swapcase. Unicode case mapping is not always one input code point to one output code point. Casefold can expand characters, so normalized text length and byte encoding may change.
prefix and suffix: startswith/endswith/removeprefix/removesuffix. startswith and endswith can accept a tuple of candidates and optional bounds; remove-prefix/suffix return the original value when no exact match exists.
search and count: index/rindex/rfind/count. Search scans the string using implementation-optimized algorithms; repeated searches over a growing input can still create quadratic work.
partitioning: partition/rpartition/splitlines. The methods allocate new strings/tuples and preserve enough structure to distinguish a missing separator from an empty field.
character tests: isalpha/isdigit/isdecimal/isnumeric/isalnum/isspace/isidentifier. They return true only when every character satisfies the property and the string is non-empty. isidentifier checks lexical shape but not whether the word is a Python keyword.
translation and encoding: maketrans/translate/encode. maketrans builds the integer-keyed mapping consumed by translate. Encoding is a boundary operation; decoding reverses bytes to text only under the correct codec.
Read these as one system: case conversion: lower/upper/casefold/title/capitalize/swapcase establishes the starting contract, prefix and suffix: startswith/endswith/removeprefix/removesuffix changes how that contract is executed or represented, and translation and encoding: maketrans/translate/encode exposes a later boundary or failure condition. A local optimization is useful only when the combined behavior stays correct and observable.
Mistakes that change program meaning: Complete string method reference
| Risk | Why it matters |
|---|---|
| case conversion: lower/upper/casefold/title/capitalize/swapcase | Do not use lower() as a universal international identifier or authorization normalization rule without a specified Unicode policy. |
| prefix and suffix: startswith/endswith/removeprefix/removesuffix | They do not validate the remainder of a protocol or filename; file.jpg.exe still ends with .exe. |
| search and count: index/rindex/rfind/count | Testing if text.find(x): is wrong because index zero is falsey and -1 is truthy. |
| partitioning: partition/rpartition/splitlines | Plain split(':', 1) returns a different shape when the separator is absent; choose intentionally. |
| character tests: isalpha/isdigit/isdecimal/isnumeric/isalnum/isspace/isidentifier | Unicode numeric characters can pass isnumeric but still fail int(), so parsing remains the authority. |
| translation and encoding: maketrans/translate/encode | Ignoring decode errors can silently lose or alter data, while repeatedly encoding/decoding adds work and ambiguity. |
Code it, observe it, explain it: Complete string method reference
- Foundation: implement or demonstrate case conversion: lower/upper/casefold/title/capitalize/swapcase with one valid input and one invalid input. Record the exact output or failure.
- Integration: combine case conversion: lower/upper/casefold/title/capitalize/swapcase with prefix and suffix: startswith/endswith/removeprefix/removesuffix. Explain which component owns validation and cleanup.
- Production: design a test or experiment that exposes the failure described for translation and encoding: maketrans/translate/encode. State the metric, assertion, or query plan that proves the correction.
What a strong checkpoint answer contains
- A precise boundary and typed or validated input.
- One named guarantee, not only a library call.
- A negative case that fails for the intended reason.
- Cleanup, transaction, retry, or cancellation behavior where applicable.
- Evidence: assertion, command output, plan, trace, metric, or accessible UI state.
Complete worked example
This example integrates the chapter rather than demonstrating an isolated method.
1from collections.abc import Iterable2
3def report(name: str, scores: Iterable[float]) -> str:4 clean = [float(score) for score in scores]5 if not clean:6 raise ValueError("at least one score is required")7 if any(not 0 <= score <= 100 for score in clean):8 raise ValueError("scores must be between 0 and 100")9 average = sum(clean) / len(clean)10 grade = "A" if average >= 90 else "B" if average >= 75 else "C" if average >= 60 else "D"11 return f"{name.strip().title():<18} {average:6.2f} {grade}"12
13print(report(" dev gupta ", [81, 94, 88]))Expected result
1Dev Gupta 87.67 BLine-by-line reading
| Line | Code | Explanation |
|---|---|---|
| 1 | from collections.abc import Iterable | Imports the named dependency; import executes the module once per interpreter cache and binds selected names here. |
| 3 | def report(name: str, scores: Iterable[float]) -> str: | Defines a function; its parameters form the explicit input boundary. |
| 4 | clean = [float(score) for score in scores] | Computes or receives a value and binds it for the next step; the referenced object remains separate from the name. |
| 5 | if not clean: | Evaluates the condition and enters this branch only when it is truthy. |
| 6 | raise ValueError("at least one score is required") | Stops the happy path with a deliberate exception carrying the boundary failure. |
| 7 | if any(not 0 <= score <= 100 for score in clean): | Evaluates the condition and enters this branch only when it is truthy. |
| 8 | raise ValueError("scores must be between 0 and 100") | Stops the happy path with a deliberate exception carrying the boundary failure. |
| 9 | average = sum(clean) / len(clean) | Computes or receives a value and binds it for the next step; the referenced object remains separate from the name. |
| 10 | grade = "A" if average >= 90 else "B" if average >= 75 else "C" if average >= 60 else "D" | Computes or receives a value and binds it for the next step; the referenced object remains separate from the name. |
| 11 | return f"{name.strip().title():<18} {average:6.2f} {grade}" | Returns the observable result to the caller and ends this invocation. |
| 13 | print(report(" dev gupta ", [81, 94, 88])) | Emits the example's observable output. |
Step-by-step execution
- Python executes the module top to bottom, creating imported names, constants, classes, and function objects before the example call runs.
- The call creates a frame, binds arguments to local names, and validates or normalizes each boundary value before deriving the result.
- Expressions evaluate left to right subject to Python's short-circuit rules; container operations allocate objects and retain references described in the memory section.
- A deliberate exception immediately begins stack unwinding; otherwise
returnpasses the result reference to the caller and the frame becomes collectible when no suspended work retains it. - The final print or assertion exposes the observable value, and edge-case tests repeat the same trace with empty, invalid, duplicate, or worst-shape input.
Common mistakes and professional corrections
| Area | Common failure | Better engineering choice |
|---|---|---|
| Variables & data types | Truthiness can collapse distinct states: 0, '', empty containers, and None are all falsey but do not mean the same thing. | Choose the type that models the domain and use decimal.Decimal for exact base-10 money rather than binary float. |
| Control flow | Deep nesting and mixed and/or expressions without parentheses hide precedence and missed cases. | Use early returns and named predicates to keep business rules flat and auditable. |
| Functions & scope | A mutable default such as items=[] is shared by every call and accumulates state. | Use keyword-only options for clarity and None plus initialization inside the function for mutable defaults. |
| Comprehensions | Side effects, nested conditions, or expensive repeated expressions make a comprehension harder to understand than a loop. | Use it for one clear transformation/filter and a generator expression for lazy consumption. |
| String formatting | Formatting is presentation, not localization or SQL/shell escaping; never treat it as an injection defense. | Use f-strings for developer-controlled templates and explicit specifiers for stable presentation. |
| Complete string method reference | Do not use lower() as a universal international identifier or authorization normalization rule without a specified Unicode policy. | Use casefold()—often with Unicode normalization—for caseless identifiers only when the domain permits it; preserve the original for display. |
Interview and review notes
- Define the central abstraction without naming a library function.
- Trace one request, call, query, message, render, or state transition from input to observable result.
- Compare two alternatives from this chapter by guarantee, cost, and failure behavior.
- Explain the most likely production bug and the test or metric that reveals it.
- State what remains authoritative after process loss, retry, reconnect, or deployment.
Practice set
Easy
- Define every bold term in the concept tables in one precise sentence.
- Reproduce the focused examples and annotate the value or state after each important line.
- Explain the chapter progression diagram aloud in two minutes.
Medium
- Replace one convenient default with an explicit policy for validation, timeout, ordering, pagination, cleanup, or error handling.
- Write a negative test for each topic group.
- Compare the measured behavior before and after one justified change.
Hard
- Combine all topic groups into one thin vertical slice.
- Inject a realistic failure at the most important external boundary and prove recovery.
- Write a one-page design note covering ownership, trade-offs, security, observability, and rollback.
Chapter submission
Submit:
- source code or reproducible commands;
- automated tests plus one deliberately failing-before-fix test;
- captured output, query plan, trace, screenshot, or metric;
- a 300–500 word explanation of the execution flow and one rejected alternative;
- a short README with setup, versions, limitations, and cleanup steps.
- Continue with the CLI Grade Calculator project workshop.
Self-review rubric
| Dimension | Beginning | Competent | Professional |
|---|---|---|---|
| Explanation | Names APIs | Explains behavior | Connects guarantees, internals, and trade-offs |
| Implementation | Happy path only | Validated and tested | Clear ownership, failure recovery, and cleanup |
| Evidence | Manual claim | Repeatable output | Tests plus meaningful measurement or inspection |
| Communication | Steps missing | Reproducible README | Decisions, limits, and alternatives are explicit |
Roadmap coverage checklist
- To do: Variables & data types: int/float/str/bool/None
- To do: Variables & data types: type conversion: int()/str()/float()
- To do: Variables & data types: id() and is vs ==
- To do: Variables & data types: constants convention
- To do: Control flow: if/elif/else + nested conditions
- To do: Control flow: for: range()/enumerate()/zip()
- To do: Control flow: while + break/continue/else
- To do: Control flow: ternary expressions
- To do: Control flow: match/case (Python 3.10+)
- To do: Functions & scope: def/return/default args/args/*kwargs
- To do: Functions & scope: LEGB scope rule
- To do: Functions & scope: lambda functions
- To do: Functions & scope: closures
- To do: Comprehensions: list comp vs for loop
- To do: Comprehensions: dict comp + filtering
- To do: Comprehensions: set comp for deduplication
- To do: Comprehensions: nested comprehensions
- To do: String formatting: f-strings + format specifiers
- To do: String formatting: format() method
- To do: String formatting: Template strings
- To do: String formatting: strip/split/join/replace/find
- To do: Complete string method reference: case conversion: lower/upper/casefold/title/capitalize/swapcase
- To do: Complete string method reference: prefix and suffix: startswith/endswith/removeprefix/removesuffix
- To do: Complete string method reference: search and count: index/rindex/rfind/count
- To do: Complete string method reference: partitioning: partition/rpartition/splitlines
- To do: Complete string method reference: character tests: isalpha/isdigit/isdecimal/isnumeric/isalnum/isspace/isidentifier
- To do: Complete string method reference: translation and encoding: maketrans/translate/encode
Quick revision
- Variables & data types: connect the surface API to its guarantee, lifecycle, failure boundary, and evidence.
- Control flow: connect the surface API to its guarantee, lifecycle, failure boundary, and evidence.
- Functions & scope: connect the surface API to its guarantee, lifecycle, failure boundary, and evidence.
- Comprehensions: connect the surface API to its guarantee, lifecycle, failure boundary, and evidence.
- String formatting: connect the surface API to its guarantee, lifecycle, failure boundary, and evidence.
- Complete string method reference: connect the surface API to its guarantee, lifecycle, failure boundary, and evidence.
- Re-read the worked-example execution trace instead of memorizing isolated syntax.
- If you cannot name the owner of state and cleanup, the design is not yet complete.
Mastery check
How well can you recall this?
Finished this lesson?