Quiz 2
Registry Synced

Python Quiz 1 revision atlas — Weeks 1–4

1906 words
10 min read
2026-07-19

Reading compass

Now · The exam-proof loop

Python Quiz 1 revision atlas — Weeks 1–4

Use: a last-mile study chapter for the Python concepts covered in the May 2026 Weeks 1–4 guide. It contains original examples and method explanations—not a substitute for a live assessment or a source of active-answer keys. For completed archive material, use the May 2026 completed archive and distinguish embedded official solutions from study reconstructions.

The exam-proof loop

When a question looks unfamiliar, do not search your memory for a matching output. Run this loop:
  1. Classify the object. Is it a value, expression, string, condition, loop, collection, or function call?
  2. Name the rule. For example: “slice stop is excluded”, “elif is tested only if earlier branches failed”, or “a set removes duplicate values”.
  3. Trace a tiny case. Write the current state after each meaningful step.
  4. Test the boundary. Empty input, zero, equality, first/last index, a negative number, or a repeated item usually exposes the mistake.
  5. State the result and its type. An output without the reason is a guess; a reason without the output is incomplete.

Taxonomy at one glance

FamilyCore questionSmall vocabularyReliable check
Values and typesWhat kind of thing is this?literal, object, type, conversion, truthinessPredict both value and type.
ExpressionsHow does it evaluate?operand, operator, precedence, associativityParenthesise the next operation.
StringsWhich characters are selected?index, slice, immutable, escapeMark index positions, including negatives.
DecisionsWhich single path runs?predicate, branch, boundary, short-circuitBuild a three-row decision table.
IterationWhat is true after each pass?invariant, counter, accumulator, progressTrace two passes and name the invariant.
CollectionsDoes order/duplication/mutation matter?list, set, membership, aliasAsk which information must be preserved.
FunctionsWhat transformation is promised?parameter, argument, return, contractWrite input, output, assumptions, edge case.

1. Values, types, and expressions

Definitions that prevent most Week 1 errors

  • A literal is source-code notation for a value: 17, 2.0, '17', and True are all literals.
  • A name binding associates a name with an object. score = 17 is a binding, not a mathematical equality claim.
  • A type determines which operations make sense. 17 + 2 is numeric addition; '17' + '2' is concatenation.
  • Conversion deliberately changes representation: int('17') turns text into an integer. It is not the same as a string merely looking like a number.
  • Truthiness is Python’s Boolean interpretation of a value. 0, '', [], {}, and None are falsy; many other values—including 'False'—are truthy.

Operator decision chart

OperatorMeaningPredictive trap
/division producing a float6 / 2 is 3.0, not 3.
//floor divisionit moves down the number line; -7 // 3 is -3.
%remainder compatible with floor divisioncheck it with a == (a // b) * b + (a % b).
**exponentiationevaluate before multiplication.
==value equalityit does not ask whether two names are the same object.
isobject identityuse mainly for sentinels such as x is None.

Original worked example: evaluate, then explain

Predict 7 // 2 + 0.5 * 4.
  1. Types entering: two integers and one float.
  2. Precedence: // and * are done before +.
  3. 7 // 2 becomes 3; 0.5 * 4 becomes 2.0.
  4. 3 + 2.0 becomes 5.0.
  5. The final type is float because mixed integer/float arithmetic yields a float.
Common doubt: “Why is -7 // 3 not -2?” Python uses floor, not truncation. -2.333… lies between -3 and -2; the floor is the lower integer, -3.

2. Strings, indexing, slicing, and decisions

The string model

A string is an ordered, immutable sequence of characters. “Immutable” means a string operation creates a new string rather than changing a character in place.
For word = 'orbit':
characterorbit
positive index01234
negative index-5-4-3-2-1
The slice word[start:stop] includes start and excludes stop. Therefore word[1:4] is 'rbi'; its length is 4 - 1 = 3. This half-open rule lets adjacent slices join without overlap: word[:2] + word[2:] reconstructs word.

Conditional taxonomy

  • A predicate is an expression intended to be true or false.
  • if / elif / else is an ordered selection: the first true branch runs; later branches are skipped.
  • and requires both conditions to be truthy; or accepts the first truthy alternative; not reverses truthiness.
  • Short-circuiting means Python may not evaluate the right operand when the left already decides the result. This helps safety: items and items[0] never indexes an empty list.

Original worked example: boundary-first classification

Classify a score as below, meets, or exceeds a target of 50.
python
if score < 50:
    label = 'below'
elif score == 50:
    label = 'meets'
else:
    label = 'exceeds'
The decisive boundary is score == 50. A frequent error is writing if score <= 50 first, which makes an intended meets branch unreachable.
Common doubt: “Can I use three separate ifs?” You can when several actions may happen. Use if / elif / else when categories are mutually exclusive and exactly one outcome should be selected.

3. Loops: state, progress, and proof

What every loop needs

IngredientQuestion to askExample
Initial stateWhat is true before the first pass?count = 0
PredicateWhen should work continue?while index < len(values)
UpdateWhat changes on this pass?count += 1
ProgressWhy will it stop?index increases toward len(values)
InvariantWhat remains true after every pass?count equals qualifying items seen so far.
Use for when an iterable provides the next item naturally. Use while when repeated work is controlled by a changing condition. A while loop without a clear progress mechanism is an infinite-loop risk.

Original worked example: trace a counter and accumulator

python
total = 0
count = 0
for value in [3, -1, 4, 0]:
    if value > 0:
        total += value
        count += 1
passvaluevalue > 0total after passcount after pass
start00
13true31
2-1false31
34true72
40false72
The invariant is: after each pass, total is the sum and count is the number of positive values seen so far. That sentence is the proof plan.
Common doubt: “Is zero positive?” No; value > 0 excludes it. Replacing > with >= changes the contract, so do it only deliberately.

4. Lists, sets, and functions

Collection choice is a data-requirement decision

NeedPreferWhy
preserve order or duplicateslistlists are ordered and mutable.
test uniqueness/membershipseta set stores unique hashable values.
remember first occurrence orderlist + setlist preserves display order; set gives fast “seen?” checks.
Aliasing warning: other = values makes two names refer to the same list. Mutating one may affect the other. other = values.copy() makes a shallow separate list.

Function contract template

Before writing a function, fill this in:
  1. Inputs: names, expected types, and allowed values.
  2. Output: type and exact meaning of returned result.
  3. Assumptions: what the caller must supply.
  4. Boundary policy: empty, zero, repeated, or invalid input.
  5. Example: one ordinary input/output pair.
python
def has_repeat(items):
    """Return True exactly when a list contains a repeated item."""
    seen = set()
    for item in items:
        if item in seen:
            return True
        seen.add(item)
    return False
Step by step: start with no seen values; before each pass, seen contains exactly the earlier items; a membership hit proves repetition; if the loop finishes, no earlier/current pair matched. return sends a result to the caller; print would only display text and is not a replacement for the contract.

The five confusion pairs

Do not blurKeep separate by asking
= and ==“Am I binding a name or comparing values?”
/ and //“Do I need ordinary division or floor division?”
index and slice“Do I want one character or a sequence?”
for and while“Do I have an iterable, or a condition-controlled process?”
print and return“Should the caller receive a value, or am I only displaying one?”

A 45-minute no-panic protocol

  1. 8 minutes — vocabulary. Read the taxonomy table aloud; define each bold term without looking.
  2. 12 minutes — prediction. Do six tiny expressions, two slices, and two Boolean predicates. Write value plus type.
  3. 12 minutes — traces. Draw two loop tables, including a boundary value.
  4. 8 minutes — contracts. Write two function contracts before any code.
  5. 5 minutes — error audit. For every miss, label it: representation, rule, control-flow, boundary, or trace error. Fix the category, not just that one answer.

Original retrieval set

Try these on paper first. Each is deliberately new rather than copied from a course assessment.
  1. Predict the value and type of (9 - 4) / 2, 9 % 4, and 'ha' * 3.
  2. For name = 'delta', state name[-1], name[1:4], and why name[4:1] is empty.
  3. Build a decision table for “free shipping only when subtotal is at least 500 and the address is verified.” Include the exactly-500 row.
  4. Trace a loop that totals even numbers in [2, 5, 6, 7]; state its invariant.
  5. Write a contract for unique_count(items). What should it return for [] and [4, 4, 9]?

Self-check standard

Your answer is ready when you can provide the rule, a trace or tiny example, and the boundary case. If any piece is missing, revisit that taxonomy row rather than cramming more outputs.

Responsible discovery references

These are discovery references, not authorities for current IITM rules or answer keys. Cross-check course scope and policy against official course material.
  • IITM Study OS course library — a large course/notes/practice catalogue useful for finding a topic label or study format.
  • QuizPractice — a question-paper practice index; use only material you are permitted to use and keep active assessment boundaries intact.
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.