Ex 18: Parcel Scanning System
Problem
Automate a parcel scanning system for a warehouse. We need to process a list of barcodes and handle damaged items or critical errors.
Rules
- Define
scan_parcels(parcel_codes: list[str]) -> list[str]. - If a barcode is "DAMAGED", skip it and log "Skipped damaged parcel".
- If a barcode is "STOP", exit immediately and log "Critical error: Stopping scan".
- Use a
for-elseblock to log "All parcels scanned successfully" only if the scan was not stopped.
Boilerplate
Copy below code and paste to our IDE for head start.
# Write our code inside this function
def scan_parcels(parcel_codes: list[str]) -> list[str]:
pass # remove this
# Call with test data
print(scan_parcels(["ABC", "DAMAGED", "XYZ"]))
Expected Output
['Scanned parcel: ABC', 'Skipped damaged parcel', 'Scanned parcel: XYZ', 'All parcels scanned successfully']
Solution
Only view the solution after trying our best.
Show solution
def scan_parcels(parcel_codes: list[str]) -> list[str]:
messages: list[str] = []
for barcode in parcel_codes:
if barcode.lower() == "damaged":
messages.append("Skipped damaged parcel")
continue
elif barcode.lower() == "stop":
messages.append("Critical error: Stopping scan")
break
else:
messages.append(f"Scanned parcel: {barcode}")
else:
# Loop finished without hitting "STOP"
messages.append("All parcels scanned successfully")
return messages
# Test call
print(scan_parcels(["ABC", "DAMAGED", "XYZ"]))
Details
The for-else block is the cleanest way to handle the "all successful" message. It avoids the need for a boolean flag (like was_stopped = False) to check if the loop was interrupted by the break statement.