Clamp negative stock to zero
Write a function that returns the supplied stock level unchanged when it is zero or positive. If it is negative, return 0. Use one if statement and a single final return statement.
Complete Listing 1. Save the completed code as clamp_stock.py and run it to check the supplied assertions.
def clamp_stock(stock: int) -> int:
result = stock
# Replace a negative result with zero.
return result
# Above the threshold: returned unchanged
got = clamp_stock(8)
assert got == 8, f"stock 8: expected 8, got {got!r}"
# At the threshold: zero is not negative
got = clamp_stock(0)
assert got == 0, f"stock 0: expected 0, got {got!r}"
# Below the threshold: replaced by zero
got = clamp_stock(-3)
assert got == 0, f"stock -3: expected 0, got {got!r}"
# Your case: which stock level is most likely to break it?
# got = clamp_stock(___)
# assert got == ___, f"stock ___: expected ___, got {got!r}"
TipHint
assert conditionchecks a Boolean condition. A true condition produces no output; a false condition raisesAssertionError. For example,assert 2 + 3 == 5passes.