← Complete program

Chapter 5 · Course 4 c05-m04

How do you examine every receipt?

Your goal Visit every receipt, count distinct IDs, and calculate a total without treating copies as new events.

The lesson, the vocabulary, the worked example and the mission are separate blocks. You can follow them in order or return to the one you need.

Video explanation

This English explanation has English subtitles. Its examples may use a separate practice dataset; use the data stated in the written mission for your answers.

01

Story · optional context

The story so far

You are the new data hire at Aster Motors. After Luca's crash and Noctis 01's disappearance, a log wrongly implicates you in a release. Voss wants you suspended. Mara Sol and investigator Imani now have several receipts, including copies. They want to read every row without missing the last one or counting one identifier twice.

You can start without earlier story. A Python list [] holds several values; a dictionary {} holds one receipt's fields. This course repeats a check across receipts on paper or in Python.

02

Before the lesson

Purpose of this course

Visit every receipt, count distinct IDs, and calculate a total without treating copies as new events.

Topics covered

Read a for loop that examines every list element.; Use range() and enumerate() to understand positions and passes.; Maintain a count and a total updated each pass.; Meet set, a collection of unique IDs, and flag copies rather than hiding them.

What you will learn

  • Read a for loop that examines every list element.
  • Use range() and enumerate() to understand positions and passes.
  • Maintain a count and a total updated each pass.
  • Meet set, a collection of unique IDs, and flag copies rather than hiding them.

PART 1 · THE LESSON

Understand step by step

1

Lesson · explanation

A loop examines rows one after another

A list might hold two receipts or two hundred. Writing a separate instruction for each would take too long and make it easy to forget one. A loop repeats an action. for receipt in receipts: means give each element of receipts the temporary name receipt and follow the loop's instructions. At each pass, receipt means the current row.

Imagine an inspector holding a stack of cards. She reads the first, checks it, puts it down, and takes the next. She stops when no cards remain. A for loop follows that rhythm. It does not choose the rule by itself; the indented code inside gives it a task, just like the inspector's written instructions.

In Python, lines belonging to the loop move to the right. For example, after for receipt in receipts:, an indented line print(receipt) displays each card. Four spaces show that displaying repeats. A line back at the left margin runs after the loop. Forgetting the indentation can stop the code or repeat the wrong action.

The mission has four rows: R31, its copy, R32, and R33. The loop will examine all four, including the copy. Examining a copy does not mean adding it to the total. The rule inside the loop will decide what to count and what to flag, using a set of IDs already seen.

Pause and think

If receipts has four rows, how many passes does for receipt in receipts: make?

See the explanation

Four passes, one for each row, including any copy.

2

Lesson · explanation

range repeats a known number of times

Sometimes you want to repeat an action three times without having three named receipts. for number in range(3): gives the numbers zero, one, and two. There are three passes, but it never gives three. Python starts at zero and stops before the limit given to range(). This resembles list indices.

Picture three squares on paper labelled 0, 1, and 2. The inspector touches each once. She touches three squares without touching one labelled 3. range(3) is useful when you need a planned number of repetitions. for receipt in receipts is often clearer when you need to read the receipts themselves.

With four receipts, range(4) gives the indices zero through three. You could fetch each receipt using these numbers, but that adds a step to understand. A beginner may prefer for receipt in receipts to focus on documents. Use range() when passage numbers or positions are actually needed.

Do not use range(4) and think the fourth pass has value four. The list indices are zero, one, two, and three. This distinction helps Mara locate the photocopy of R31 when Imani asks where it appears. The human second row has Python index one.

Pause and think

What numbers come from range(4), and why is four absent?

See the explanation

Zero, one, two, and three. Four is the stopping limit, not an included value.

3

Lesson · explanation

enumerate pairs a position with each element

When you cite a row to another person, you might want to say row one rather than Python index zero. enumerate(receipts, start=1) supplies a pair on every pass: a human row number and the matching receipt. for position, receipt in enumerate(receipts, start=1): receives both separately. Four receipts get displayed positions one, two, three, and four.

Imagine a teacher giving numbers to pupils already standing in order. The first pupil receives badge one, but their internal list index stays zero. The badge makes conversation easier; it does not move the pupil. Similarly, start=1 changes the first number from enumerate(), not the list contents or indices.

If the R31 copy follows original R31, its human position is two and its Python index is one. Both numbers are correct under different conventions. In a report, say second row, Python index one when precision matters, so everyone finds the same card.

You can first loop over receipts without numbers and add enumerate() when the mission asks for positions. Learning one tool at a time keeps the loop understandable. The main rule remains to examine every row and record what happened to it.

Pause and think

For four receipts, what human positions does enumerate(receipts, start=1) give, and what is the second row's Python index?

See the explanation

It gives positions one through four. The second row has Python index one.

4

Lesson · explanation

A counter and a total answer different questions

Before the loop, prepare count = 0 and total = 0. When you read a distinct receipt for one part, count = count + 1 and total = total + 1. If the next distinct receipt lists two parts, count becomes two while total becomes three. The counter asks how many distinct receipts; the total asks how many parts they describe.

Imagine two boxes of tokens, one for documents and one for parts. A receipt for three parts adds one token to the document box and three to the part box. If you use one box for both questions, you might report three receipts when there is only one. Name each variable for what it measures.

R31 lists quantity one, R32 quantity two, and R33 quantity three. If they have distinct IDs and you leave the copy out of the sums, count ends at three and total at six. The sum one plus two plus three counts parts received, because every row says received. The same total cannot be called six parts released.

A loop faithfully applies your rule even if that rule mixes different actions. Before starting, state aloud what you are counting and which rows support it. If a released row appeared among the received rows, it would need separate handling. Python cannot guess the units or meanings of fields.

Pause and think

Three distinct receipts list one, two, and three received parts. What are count and total?

See the explanation

count is three distinct receipts; total is six parts recorded as received.

5

Lesson · explanation

A set helps remember IDs already seen

A list preserves order and may contain the same ID more than once. A set is useful here as memory of IDs already encountered. seen = set() makes an empty set, then seen.add('R31') places R31 in it. Adding R31 again does not create a second set element. if identifier in seen: checks whether it has appeared already.

Think of a checklist kept by the inspector. When R31 arrives the first time, she writes R31. When its photocopy arrives, she sees the mark. She keeps the photocopy for the case file but does not treat it as a new ID. The set is her memory sheet, not a bin for repeated documents.

In the mission, the four rows have original IDs R31, R31, R32, and R33. After the first pass, seen contains R31. On the second, the ID is already there: flag the copy without increasing count or total. Then add R32 and R33 to seen and the counts. The result is three distinct IDs and six parts received according to the unique rows.

Two receipts bearing one ID but different quantities need extra care. Keep both, flag the disagreement, and inspect originals. The set detects the repeated identifier but cannot decide which quantity is correct. Quietly deleting a row could hide evidence of an error or fraud.

Pause and think

What is in seen after R31, its copy, and R32? Should the copy disappear from the case file?

See the explanation

seen contains R31 and R32. The copy stays in the file, labelled for review, but does not count as a new ID.

6

Lesson · explanation

Explain every pass before publishing the result

A tracking table helps verify a loop. Write one row per receipt with its human position, ID, quantity, answer to already seen, then the values of count and total after that pass. Original R31 leaves one and one. Its copy leaves one and one again. R32 leaves two and three; R33 leaves three and six.

Imagine a camera filming the inspector card by card instead of only recording her final announcement. If someone disputes the total, the film shows when it changed. Your table does the same. It also proves the R31 copy was examined and flagged rather than silently added twice.

For Mara's report, keep three distinct IDs, six parts recorded as received, and one row copying R31 as separate statements. Each describes a different thing. None of the four rows says released. Even if Voss speaks of four departures, these receipts do not establish them.

Do not jump from that finding to no departure ever happened. You have examined only the authorized copies Imani gave you; other records may exist. If R31 rows disagree, pause the public total and request originals. An explained loop helps the investigation without turning absence from this batch into a universal claim.

Pause and think

After the four mission rows, what may Mara report without claiming the case is solved?

See the explanation

Three distinct IDs describe six parts recorded as received; the fourth row copies R31. These receipts do not prove departures.

Code · read each line

Visit three rows and keep two IDs

receipts = [{'id': 'R21', 'quantity': 2},
            {'id': 'R21', 'quantity': 2},
            {'id': 'R22', 'quantity': 1}]
seen = set()
duplicates = []
count = 0
total = 0
for position, receipt in enumerate(receipts, start=1):
    if receipt['id'] not in seen:
        seen.add(receipt['id'])
        count = count + 1
        total = total + receipt['quantity']
    else:
        duplicates.append(receipt)
print(count)
print(total)
print(len(duplicates))

The loop reads three rows, but the second R21 is already in seen. It shows 2 distinct receipts and 3 parts from R21 and R22. Preserve the copy outside the total.

PART 2 · WATCH IT WORK

A complete worked example

Follow each step, then the result

Worked example: a copy in the middle

Rows are R21 quantity 2, R21 copy quantity 2, then R22 quantity 1. Find distinct receipts and their total quantity.

  1. Start with empty seen, count = 0, and total = 0.
  2. Pass 1: R21 is new. Add it; count becomes 1 and total 2.
  3. Pass 2: R21 is already in seen. Preserve the copy for review without increasing count or total.
  4. Pass 3: R22 is new. Add it; count becomes 2 and total 3.
  5. Stop after the last row. Result: 2 distinct receipts and 3 parts according to them, subject to checking originals.
What this shows

A loop checks every row; the set keeps a copy from silently increasing the total.

How this helps with your mission

In the worked example, the loop reads three rows, keeps a copy of R21, and changes count and total only for R21 and R22. Repeat that method with four mission rows: R31, its copy, R32, and R33. enumerate(..., start=1) gives human positions one through four while indices remain zero through three. The seen set catches the second R31. count finishes at three and total at six parts received. This answers Voss without turning received into released or hiding a conflicting copy.

PART 3 · YOUR TURN

Use the lesson to solve the mission

Story scene · practical task

Mission: check Voss's total

Voss points to four rows and claims “four departures.” Imani gives you authorized copies: R31 quantity 1, R31-copy quantity 1 with the same original ID, R32 quantity 2, and R33 quantity 3. Every row says “received,” not “released.” The story's meeting is near; take the time you need. Mara asks for a row-by-row report.

Your task

  1. Give the human positions from enumerate(receipts, start=1) and the Python list indices.
  2. Describe how seen, the count, and total change at each row.
  3. Report distinct IDs and total received quantities, flagging the copy.
  4. Explain why this does not prove four departures and what to do if two R31 rows disagree on quantity.

How to know you have succeeded

  • You give positions 1–4 and indices 0–3 separately.
  • You do not add the R31 copy to count or total, but flag it.
  • You get 3 distinct IDs and 1 + 2 + 3 = 6 parts recorded as received.
  • You separate received from released and request review of conflicting copies.
Open this mission in the browser workspace

Try code or SQL and keep a local draft. The mission questions are checked separately below.

Check the facts in your mission

Answer each factual question, then write your report in your own words. The program checks the choices; compare the report with the worked answer below.

1. What are the human positions and Python indexes of the four lines?
2. What should happen on the second pass, at the copy of receipt R31?
3. After R31 (1), its copy (1), R32 (2), and R33 (3), what careful result do you get?
4. If original and copy R31 have different quantities, what should you do?
See the worked answer
  1. enumerate(..., start=1) gives positions 1, 2, 3, 4; list indices are 0, 1, 2, 3.
  2. R31: seen {R31}, count 1, total 1. R31 copy: no increase. R32: seen {R31, R32}, count 2, total 3. R33: seen {R31, R32, R33}, count 3, total 6.
  3. Report: “Three distinct IDs describe six parts recorded as received; a fourth row copies R31.”
  4. These rows prove no departure. If two R31 rows have different quantities, keep both, flag the conflict, and inspect originals before publishing a total.

You can check every receipt with a careful rule. Next, you will make that rule a reusable, testable function.

Before you leave

Remember this

  • A for loop examines each list element under the rule in its indented block.
  • range(4) gives zero through three; enumerate(..., start=1) gives human positions one through four.
  • A receipt counter and a parts total answer different questions.
  • A set remembers IDs already seen and helps flag copies.
  • Keep copies and conflicts visible in the file even when they do not increase distinct-ID totals.
  • A loop can total received parts; it cannot prove releases absent from these rows.
A–Z

Part of the lesson · keep nearby

New words, explained

These are the names of ideas used in the lesson above. Return here whenever a word feels unfamiliar.

Loop
A rule repeated for every element until none remain.
for
Python's word for “for each…”.
range()
A number sequence: range(3) gives 0, 1, 2, not 3.
enumerate()
Gives a position together with each element.
Counter
A number increased by 1 when a condition is met.
Total
A sum increased by the quantity of each accepted receipt.
set
A collection of distinct values useful for remembering IDs already seen.