Quiz 2
Registry Synced

May 2026 Python — Weeks 1–4 study guide

2352 words
12 min read
2026-07-18

Reading compass

Now · Week 1 — values, types, and expressions

Python, Weeks 1–4: a reliable mental model

This guide is for learning, not for answering the current graded assignments. Use it to predict, trace, and explain code you write yourself.

Week 1 — values, types, and expressions

A value is data currently represented by the program; a type is the set of operations the language gives that value. int, float, str, and bool are distinct types, even when their printed forms look similar. An expression combines values and operators to produce one value. The practical order of work is: identify operand types → apply operator semantics → predict result type → evaluate.
Python’s arithmetic operators include +, -, *, /, //, %, and **. / produces a floating-point result; // is floor division, so it rounds down on the number line rather than merely truncating toward zero. == asks whether two values are equal; is asks whether two names refer to the same object, which is a different question. Boolean operators return operands in some contexts, so do not assume and and or always produce literal True or False.
Check yourself: explain why a string that looks numeric is still text until conversion. Then invent one expression whose value is valid but whose type surprises a beginner.

Week 2 — strings and decisions

A string is an ordered, immutable sequence of Unicode characters. Indexing selects one character; slicing selects a contiguous or stepped subsequence. The half-open slice rule s[start:stop] includes start and excludes stop, which makes slice lengths compose cleanly. Negative indices count from the end. Escapes such as \n, \t, \\, and quotes inside strings change how a literal is written, not the underlying idea of a sequence.
A conditional chooses a branch from a Boolean predicate. Write the predicate in plain language first, then translate it. An if chain is ordered: the first true branch runs, and later branches are skipped. Common mistakes are confusing assignment with comparison, forgetting boundary cases, and combining conditions without parentheses when the meaning is unclear.
Check yourself: write a decision table for a simple eligibility rule with three cases: below threshold, exactly threshold, above threshold. Trace it before writing code.

Week 3 — iteration and tracing

A loop invariant is a fact that remains true before and after every iteration. It is the best tool for understanding loops. while repeats while a condition remains true and needs explicit progress toward termination. for iterates over items in an iterable and is usually clearer when the collection already exists. A counter tracks how many items satisfy a condition; an accumulator builds a total or combined result.
Nested loops multiply work: if an outer loop runs m times and an inner loop runs n times for each outer pass, the body runs m × n times. Trace a small input in a table with columns for iteration, variables, condition, and output. If you cannot trace two iterations, you do not yet understand the loop.
Check yourself: invent a loop that sums only positive values in a list. State its invariant in one sentence.

Week 4 — collections and functions

A list is ordered and mutable; a set is unordered and stores unique hashable values. Choose a list when position, duplicates, or order matter; choose a set when membership and uniqueness matter. A comprehension expresses “transform/filter every item” compactly, but a plain loop is often better while learning because its state is visible.
A function packages a named transformation. Parameters are names in the function definition; arguments are values supplied at a call. A return value is the result sent back to the caller; printing is only an observable side effect. Keep one function responsible for one coherent job, use descriptive names, and test ordinary, boundary, and invalid inputs.
Check yourself: describe when a set is the wrong choice. Then write a function contract: input, output, assumptions, and one example.

Representation lab: choose the structure for the job

Switch among a list, tuple, and dictionary, then add one value. Do not stop at the generated syntax. For each structure, explain: what does each position or key mean; may it be changed; and do duplicates/order matter? A container is not “better” in isolation—it is better only for a stated contract.
Loading Visualizer...
Start with the invariant, not the syntax
If you need “every ID seen so far, with no duplicates,” a set is a good candidate. If you need “the first arrival must remain first,” a set cannot preserve that contract by itself. State the invariant in words before selecting the collection.

The vocabulary map — words that stop you guessing

TermPrecise meaningWhy it matters in practice
literalSource-code notation for a value, such as 12, 2.5, or 'go'.A literal is written directly; a variable is a name that refers to a value.
name bindingThe association made when a name is assigned to an object.Assignment changes a binding; it does not always copy an object.
objectA runtime value with a type, identity, and sometimes mutable state.It explains why is and == answer different questions.
coercion / conversionChanging a representation, deliberately with int(), float(), or str().Never rely on a value merely looking numeric.
truthinessHow a value behaves when Python needs a Boolean.Empty sequences and zero are falsy; that is not the same as being equal to False.
predicateAn expression whose intended result is true or false.A clear predicate makes a conditional readable and testable.
iterationRepeated execution over a sequence or while a condition holds.Every loop needs state, a progress mechanism, and a stopping story.
aliasingTwo names referring to the same mutable object.Mutating through one name changes what the other observes.
contractThe input, output, assumptions, and guarantees of a function.Contracts turn “it seems to work” into a checkable claim.

A three-question interpreter habit

Whenever you read an expression, pause before evaluating it.
  1. What values and types enter? For 7 // 2 + 0.5, the inputs are two integers and one float.
  2. Which operation is done first? // happens before +, producing 3, then 3 + 0.5 produces 3.5.
  3. What type leaves? Mixed arithmetic here produces a float.
That habit is more transferable than memorising dozens of outputs. It also catches the most common Week 1 error: treating printed appearance as semantic type.

Original worked examples — method before answer

Example A: boundary-aware decision

Suppose a library rule says a book can be renewed only when days_late is zero and renewals_used is less than two. Translate the sentence into two predicates, then combine them:
python
on_time = days_late == 0
has_renewal_left = renewals_used < 2
can_renew = on_time and has_renewal_left
The point is not the syntax. The decomposition makes it easy to test the boundary: renewals_used == 2 must be rejected, and a book one day late must also be rejected. If you write the whole condition in one dense line first, those boundaries become invisible.

Example B: accumulator with an invariant

To total only positive temperatures, start with an accumulator representing the total of zero processed qualifying values:
python
total_positive = 0
for temperature in readings:
    if temperature > 0:
        total_positive += temperature
The invariant is: after each item, total_positive equals the sum of every positive reading seen so far. Trace the first two readings on paper. If the sentence remains true after each update, the loop is behaving as intended.

Example C: a function that returns rather than prints

python
def initials(first, last):
    return first[0].upper() + last[0].upper()
The contract is: inputs are non-empty strings; output is a two-character uppercase string. print(initials('Ada', 'Lovelace')) is a caller choosing to display the returned result. Keeping the function separate from display makes it reusable and easier to test.

Function-call frame lab

Loading Visualizer...
Step the program line by line. Notice the exact point at which the local initials frame exists, the point at which it disappears, and why print receives "AL" only after return has handed a value back. This distinction is the foundation for testing, composition, and debugging functions without guessing from terminal output.

Debugging taxonomy — identify the kind of wrong first

  • Syntax error: Python cannot parse the program. Read the location, then inspect the preceding delimiter, quote, or indentation.
  • Runtime error: the syntax is valid but an operation is impossible for the current state, such as indexing an empty list.
  • Logic error: the program runs but computes the wrong claim. Use a trace table and restate the intended invariant.
  • Boundary error: a condition mishandles zero, an endpoint, an empty sequence, or an exact threshold. Build those cases before the “normal” one.
  • Representation error: the data is a string when you needed a number, or a list when you needed uniqueness. Re-check the type before changing the algorithm.

Four lenses for reading Python precisely

When a program surprises you, do not ask only “what line is wrong?” Work through four lenses in order.
  1. Representation. What values exist, and what are their types? "12" + "3" is string concatenation, while 12 + 3 is arithmetic. Neither is more “correct”; the intended representation decides which operation belongs.
  2. Binding and mutation. a = b makes another name for the same object; it does not necessarily make a copy. With immutable values such as integers and strings this distinction is often invisible. With a list, a.append(4) can affect what b observes. Use b = a.copy() when a separate list is intended.
  3. Control flow. Which condition is tested, and in what order? A chained conditional is not a menu of independent checks. In if / elif / else, the first true branch owns the decision.
  4. Contract. What must a function receive, and what does it promise to return? A function that accepts an empty list needs a stated policy; otherwise “find the largest item” is underspecified, not merely buggy.

Counterexamples that teach the boundary

  • range(3) yields 0, 1, 2, not three copies of 3. The stop is excluded.
  • bool("False") is True: a non-empty string is truthy even when its characters spell a false-looking word.
  • list_a = list_b followed by list_a[0] = 9 is not evidence that assignment copies a list. It is evidence that the names are aliases.
  • return and print are not interchangeable. A returned value can be composed or tested; printed output is sent to the display and normally disappears from the caller’s computation.

Binding and mutation lab

Loading Visualizer...
First use b = a, make a prediction, then append through b. Reset to b = a.copy() and repeat the same operation. The code looks almost identical, but assignment created another name for one mutable list while copy() created a second list. This is a mutation question, not a question of whether two printed lists happen to look equal.
Original retrieval task: In your own words, distinguish these three actions: binding b to an existing list, copying a list, and rebinding b to an entirely new list. Which actions can change what a observes, and why?

A trace table you can reuse

For a loop or conditional, use a table before you run anything:
Stepinput/itempredicatestate beforeupdatestate after
0total = 0initialisetotal = 0
1first itemdoes it qualify?current totaladd or skipnew total
The table is a proof aid, not busywork. It forces you to name what every variable means. For a while loop, add a progress column: what quantity moves toward making the condition false? If you cannot fill that cell, termination has not been established.

Original retrieval lab

Attempt these without executing them; then explain your reasoning aloud.
Loading Visualizer...
  1. Predict the value and type of (5 + 1) / 2, "5" * 2, and 5 % 2. Name the operator rule behind each result.
  2. A list of readings contains [-2, 0, 4, 5]. Design a loop that counts strictly positive readings. State the invariant after the third reading.
  3. Write a function contract for is_weekend(day). What inputs are valid, what type is returned, and what should happen for an unknown spelling?
  4. Explain why a set is useful for checking whether an ID has appeared before but unsuitable when the original arrival order must be displayed.
  5. In the representation lab, create the same three values as a list and as a dictionary. State one operation that is natural for each and one requirement it cannot satisfy on its own.
Answer standard: your explanation is complete only when it includes the rule, a tiny example, and the boundary case that could fool you.

Four retrieval checks

  1. Without running code, explain why -7 // 3 differs from truncating -7 / 3 toward zero.
  2. Write a decision table for a rule with two independent conditions. Which row is easiest to forget?
  3. State an invariant for a loop that counts names beginning with A.
  4. For a function that receives a list and returns its largest value, write one ordinary case, one boundary case, and one invalid-input policy.
If you cannot say the answer aloud in plain language, do not immediately search for another code pattern. Return to the definition, draw a tiny trace, and make the program earn your confidence.
Document outline

Keep your place and jump directly to a heading.

Table of Contents
System Normal // Awaiting Context

Intelligence Hub

Navigate the knowledge graph to generate context. The Hub adapts dynamically to surface backlinks, related notes, and metadata insights.