Skip to main content

Ex 9: Delivery Charge Calculator

Problem

We’re building a delivery system for an e-commerce platform. Depending on the distance of the customer’s address, different delivery charges apply.

  • Define calculate_delivery_charge(distance) that accepts a distance in kilometers.
  • Return a specific delivery-charge string based on the distance range.
  • Preserve the correct boundaries and avoid overlapping ranges.

Rules

  • Define calculate_delivery_charge(distance: float) -> str.
  • If distance is 2 km or less, return "Delivery charge: 0".
  • If distance is greater than 2 km but not more than 5 km, return "Delivery charge: 30".
  • If distance is greater than 5 km but not more than 10 km, return "Delivery charge: 50".
  • If distance is more than 10 km, return "Delivery not available for our location.".

Boilerplate

Copy below code and paste to our IDE for head start.

# Write our code inside this function
def calculate_delivery_charge(distance: float) -> str:
pass # remove this

# Call with test data
print(calculate_delivery_charge(3.5))
print(calculate_delivery_charge(15))

Expected Output

Delivery charge: 30
Delivery not available for our location.

Solution

Only view the solution after trying our best.

Show solution
def calculate_delivery_charge(distance: float) -> str:
if distance <= 2:
return "Delivery charge: 0"
elif distance <= 5:
return "Delivery charge: 30"
elif distance <= 10:
return "Delivery charge: 50"
return "Delivery not available for our location."

# Test calls
print(calculate_delivery_charge(3.5))
print(calculate_delivery_charge(15))

Details

The first true branch wins, so it's best to put more specific ranges (like distance <= 2) at the top. This allows the subsequent elif blocks to handle any values that fall through.