M13) Boxes per pallet

A warehouse scanner sends the number of boxes in a delivery as text, such as "120". The function boxes_per_pallet in Listing 1 converts the text to a whole number and divides the boxes evenly over the pallets. For a valid delivery, the box count is nonnegative, the pallet count is positive, and the box count is divisible by the pallet count. The calls below also test invalid inputs. When the text is not a whole number, the function returns -1 so that a clerk can count the delivery by hand.

Listing 1: Dividing scanned boxes over pallets, with 4 calls (Question 1).
def boxes_per_pallet(total_text: str, pallets: int) -> int:
    try:
        total = int(total_text)
        return total // pallets
    except ValueError:
        return -1


print(boxes_per_pallet("120", 4))
print(boxes_per_pallet("96", 4))
print(boxes_per_pallet("12.5", 4))
print(boxes_per_pallet("120", 0))
TipError-type hints

You do not need to memorize the error names. int(text) raises a ValueError when the text cannot be converted to an integer. Division or floor division by 0 raises a ZeroDivisionError.

What happens when Listing 1 is run?

  1. It prints 30, 24, -1, and -1.
  2. It prints 30, 24, and 3, then stops with a ZeroDivisionError.
  3. It prints 30, 24, 3, and -1.
  4. It prints 30, 24, and -1, then stops with a ZeroDivisionError.