Repair a nested-alternative calculation

A shipping program accepts valid parcel dictionaries. A Local parcel contains kind="local" and a positive weight_kg. An International parcel contains kind="international", a positive weight_kg, and a declaration dictionary. That declaration is either Documents, with only kind="documents", or Goods, with kind="goods" and a nonnegative value_dollars.


A parcel is Local or International, and an International parcel contains a Documents or Goods declaration.


Local shipping costs 5.00 dollars per kilogram. International shipping costs 12.00 dollars plus 7.00 dollars per kilogram, with an additional 4% of declared value for Goods only. The following function fails for some valid inputs. Which correction makes it implement the stated charges for every permitted form?


Python
def charge(parcel):
    if parcel["kind"] == "local":
        return 5.00 * parcel["weight_kg"]
    declaration = parcel["declaration"]
    return (12.00 + 7.00 * parcel["weight_kg"]
            + 0.04 * declaration["value_dollars"])
Choose an answer

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 Data Definitions and Program Structure Questions: