What changes when assertions are switched off

A Python 3 script applies a list of stock changes. Expected problems raise exceptions; the final range check is an assertion.


Python
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.

Your answers

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

More Exceptions and Assertions Questions: