Python Master Course V2 — 030. Loops Project and Review
SMARTYFY · PYTHON MASTER COURSE V2 · MODULE 03 · LESSON 030/200
Loops Project — Inventory Reconciliation and Daily Sales Analyzer
Study: 90–120 minutes · Prerequisite: Lesson 029 and Lessons 021–028.
Video lesson
No video has been uploaded. This area is reserved for a verified video link or embedded player.
Learning outcomes
- Use collection traversal, nested loops, strict pairing, and accumulators.
- Build totals, counts and anomaly reports with accumulators.
- Validate transaction data and handle missing or invalid records.
- Analyze performance and verify expected results.
- Deliver a working inventory reconciliation project.
Reconcile quantities with a clear policy
Write down what missing data means
Actual minus expected defines the difference: negative is shortage; positive is surplus. The union of item keys exposes items on only one side. get(item, 0) embeds a policy: omission means a known zero, not “nobody counted this item yet.” Adopt that policy for the classroom data. A real counting workflow may need an unverified status instead.
Net and absolute variance answer different questions
differences = [-2, 3, -3]
net_difference = 0
absolute_variance = 0
for difference in differences:
net_difference += difference
absolute_variance += abs(difference)
print("Net:", net_difference)
print("Absolute variance:", absolute_variance)
Expected output:
Net: -2
Absolute variance: 8
Signed differences partly cancel. Absolute variance records discrepancy magnitude: three mismatches have net shortage 2 and total variance 8 units. These are unit counts, not monetary losses.
Validate before presenting a report
Require nonnegative integer quantities, excluding booleans. Validate every office before producing final-looking output so a late invalid value cannot leave a misleading partial report. Both expected and actual mappings are required. Keep sorting for deterministic item order.
Build in stages: verify input shape, compare one office, generalize to all offices, add both accumulators, and test boundaries. Pair aligned lists with zip(…, strict=True); unequal exhaustion raises ValueError during consumption, potentially after earlier pairs were processed.
The core project uses collection traversal and nested loops. Add while or break only when an extra requirement needs them. CSV export is optional after file handling is taught.
Progressive runnable examples
Python 3.10+; no external dependencies. Save each snippet separately and run it with python filename.py.
1. Sum transactions
transactions = [120, -30, 50]
balance = 0
for amount in transactions:
balance += amount
print(balance)
Expected: 140.
2. Skip invalid entries
records = [100, None, 250, -20]
total = 0
for value in records:
if value is None:
continue
total += value
print(total)
Expected: 330.
3. Enumerate discrepancies
expected = [100, 200, 300]
actual = [100, 195, 310]
for index, (a, b) in enumerate(zip(expected, actual, strict=True), start=1):
if a != b:
print(index, b - a)
Expected output:
2 -5 3 10
4. Stop on a critical issue
values = [10, 20, -999, 30]
for value in values:
if value == -999:
print("Critical marker found")
break
print(value)
10 20 Critical marker found
Professional capstone — Multi-office inventory reconciliation
Scenario: Compare expected and counted inventory for several offices. Report mismatches by item and calculate total differences. A negative difference means a shortage; a positive difference means a surplus. This classroom project uses synthetic data and should not be treated as an audited financial reconciliation.
offices = {
"Office A": {
"expected": {"pens": 120, "books": 45, "files": 20},
"actual": {"pens": 118, "books": 45, "files": 23}
},
"Office B": {
"expected": {"pens": 80, "books": 30},
"actual": {"pens": 80, "books": 27}
}
}
def validate_offices(offices):
if not isinstance(offices, dict):
raise ValueError("offices must be a dictionary")
for office, data in offices.items():
if not isinstance(office, str) or not office.strip():
raise ValueError("office names must be nonempty strings")
if not isinstance(data, dict):
raise ValueError("office data must be a dictionary")
for side in ("expected", "actual"):
quantities = data.get(side)
if not isinstance(quantities, dict):
raise ValueError("each office needs expected and actual dictionaries")
for item, quantity in quantities.items():
if not isinstance(item, str) or not item.strip():
raise ValueError("item names must be nonempty strings")
if type(quantity) is not int or quantity < 0:
raise ValueError("quantities must be nonnegative integers")
validate_offices(offices)
total_difference = 0
absolute_variance = 0
mismatch_count = 0
for office, data in offices.items():
print(f"--- {office} ---")
expected = data["expected"]
actual = data["actual"]
for item in sorted(expected.keys() | actual.keys()):
# Classroom policy: a missing item is a known quantity of zero.
expected_qty = expected.get(item, 0)
actual_qty = actual.get(item, 0)
difference = actual_qty - expected_qty
absolute_variance += abs(difference)
total_difference += difference
if difference != 0:
mismatch_count += 1
print(f"{item}: difference {difference:+d}")
print(f"Mismatches: {mismatch_count}")
print(f"Net quantity difference: {total_difference:+d}")
print(f"Absolute variance: {absolute_variance}")
# Boundary checks: no extra output when all checks pass.
assert (mismatch_count, total_difference, absolute_variance) == (3, -2, 8)
def summary(expected, actual):
mismatches = 0
net = 0
variance = 0
for item in expected.keys() | actual.keys():
difference = actual.get(item, 0) - expected.get(item, 0)
if difference != 0:
mismatches += 1
net += difference
variance += abs(difference)
return mismatches, net, variance
assert summary({"pens": 2}, {"pens": 2}) == (0, 0, 0)
assert summary({}, {}) == (0, 0, 0)
assert summary({"folders": 4}, {}) == (1, -4, 4)
assert summary({"a": 4, "b": 0}, {"a": 0, "b": 4}) == (2, 0, 8)
for invalid in [-1, "3", True]:
try:
validate_offices({"Test": {"expected": {"pens": invalid}, "actual": {}}})
except ValueError:
pass
else:
raise AssertionError("Invalid quantity was accepted")
try:
list(zip([1, 2], [1], strict=True))
except ValueError:
pass
else:
raise AssertionError("Unequal lists were silently truncated")
Expected output:
--- Office A --- files: difference +3 pens: difference -2 --- Office B --- books: difference -3 Mismatches: 3 Net quantity difference: -2 Absolute variance: 8
The nested dictionaries are a capstone preview: offices maps names to office records, and expected/actual map item names to quantities. Validate the entire dataset before printing any report. A missing item is treated as a known zero here; an unsubmitted count should instead be marked unverified by a workflow that requires it.
The silent assertions after the report test matched and empty datasets, missing-side items, canceling differences, rejected quantities, and unequal strict pairing.
Step-by-step: Outer iteration selects an office. Inner iteration compares the union of item keys so missing entries are not silently ignored. Differences are calculated as actual minus expected. The report counts individual mismatches and aggregates a signed net difference; always inspect individual mismatches because a net total can conceal offsetting shortages and surpluses.
Optional extensions: flag offices over a chosen variance threshold. CSV export can be added after file handling is taught; the reconciliation calculation should work and be tested before adding file output.
Common mistakes and professional practices
- Using only a net total and missing offsetting discrepancies.
- Iterating only expected keys and overlooking surplus items.
- Confusing actual-minus-expected with expected-minus-actual.
- Using
zipwith different-length sequences without detecting truncated values. - Failing to validate negative or noninteger quantities.
- Not testing empty collections and single-item offices.
Think, trace, and solve
1. Reconcile one office
Expected: pens=10, books=5. Actual: pens=8, books=8. Give each difference, mismatch count, net, and absolute variance.
Optional hint
Compute actual minus expected for each item, then take absolute values.
Reveal answer and reasoning
Pens: -2; books: +3. Two mismatches, net +1, variance 5. Signed differences partly cancel. Sorting lists books before pens.
2. Interpret a missing-side item
Expected is {“folders”: 4}; actual is empty. What does the known-zero policy report? What if no count was submitted?
Optional hint
A missing key and an unsubmitted count can mean different things.
Reveal answer and reasoning
Difference is 0 – 4 = -4. If nobody submitted a count, absence is unknown rather than a confirmed shortage. Establish the missing-data policy before calculation.
3. Diagnose a convincing zero
Differences are -6 and +6. Does net zero prove inventory matches? Give two additional values.
Optional hint
Check each item before adding signed differences.
Reveal answer and reasoning
No. There are two mismatches and absolute variance 12. Signed cancellation does not establish per-item equality.
4. Validate quantities precisely
Which of 0, 3, -1, “3”, and True satisfy type(quantity) is int and quantity >= 0? Why avoid isinstance(quantity, int) alone?
Optional hint
Check both type and sign; booleans inherit from int.
Reveal answer and reasoning
Only 0 and 3. Negative quantities, strings, and booleans are rejected. True is an instance of int in Python, so an exact type check deliberately excludes it.
5. Expose a missed surplus
Design a small test that reveals code comparing only expected keys.
Optional hint
Put an extra item only on the actual side.
Reveal answer and reasoning
expected = {"pens": 2}
actual = {"pens": 2, "clips": 7}
The union includes clips: one mismatch, difference +7, net +7, variance 7. A loop over expected alone would miss it.
Mastery checkpoint
Explain nested iteration, produce the discrepancy report, calculate both net and absolute variance, and add at least three boundary tests. Review prior loop lessons if any step is unclear.
Finish the exercises and mastery checkpoint before marking this lesson complete. Completion is stored on this browser.