A Python 3 script applies a list of stock changes. Expected problems raise exceptions; the final range check is an assertion.
def apply(stock, change): if not isinstance(change, int): raise TypeError("change must be an integer") if stock + change < 0: raise ValueError("insufficient stock") new_stock = stock + change assert 0 <= new_stock <= 500, "stock out of range" return new_stock stock = 120 rejected = 0 for change in [-30, 50, -200, 400, "5", -10]: try: stock = apply(stock, change) except ValueError: rejected += 1 print(stock, rejected)
The script is run twice: once normally, and once as python -O, which removes every assert statement. For each run the program stops with an uncaught exception. Give the value of stock at the moment the normal run stops, the value of rejected at that moment, and the name of the exception class that stops it. Then give the value of stock when the -O run stops and the exception class that stops that run. Enter the counts as whole numbers and the exception classes by their Python names.
Unlock full course notes by signing up
Stop at the first failed check
A loading simulation runs this Python code with assertions enabled and no failure handling. Each number in masses is a parcel mass in kilograms. What is total when the first assertion fails? Answer in kilograms as an exact integer.
A check that changes the log
The function below records one sensor reading. Python's list.append adds an entry and returns None. Consider two separate calls, each starting with an empty list: one with assertions enabled and one running under -O, which removes assertions. Select every correct statement.
Follow an exception through two finally blocks
The Python 3 program below validates a stock adjustment. Arrange the lines it prints in the order they appear in the output when it runs.
When matching totals hide incorrect records
A router receives 28 distinct record identifiers (IDs). Its requirement is to place every incoming ID in exactly one of two lists: sent or queued. Every ID in either list belongs to this batch, and neither list contains internal duplicates. The sent list contains 19 IDs, the queued list contains 9 IDs, and 2 IDs appear in both lists. With assertions enabled, what does the following check establish?