"cost" is not defined? Please help! UPDATE: solved


#1

Here is my entire code for Learn Python 3, Project Sal’s Shipping:

Again, near the end of my code, the traceback throws an error that “cost” is not defined. See the comment for “# Call function below to test out 4.8 lbs and 41.5 lbs output” (third last line of code). Please help!

def ground_shipping(weight):

if weight <= 2:
price_per_pound = 1.50
elif weight <= 6:
price_per_pound = 3.00
elif weight <= 10:
price_per_pound = 4.00
else:
price_per_pound = 4.75

return (weight * price_per_pound) + 20

print(ground_shipping(6.4))

premium_shipping = 125.00

def drone_shipping(weight):

if weight <= 2:
price_per_pound = 4.50
elif weight <= 6:
price_per_pound = 9.00
elif weight <= 10:
price_per_pound = 12.00
else:
price_per_pound = 14.25

return weight * price_per_pound

print(drone_shipping(1.5))

def cheapest_shipping(weight):

ground = ground_shipping(weight)
premium = premium_shipping
drone = drone_shipping(weight)

if ground < drone and ground < premium:
shipping = “Ground shipping”
cost = ground
elif drone > ground and drone < premium:
shipping = “Drone shipping”
cost = drone
else:
shipping = “Premium shipping”
cost = premium

print(“The cheapest option for you would be {cost} with {shipping}.”.format(cost, shipping))

Call function below to test out 4.8 lbs and 41.5 lbs output

cheapest_shipping(4.8) # This one does not work! Traceback says “cost not defined”
cheapest_shipping(41.5) # This one works


#2

You can format the print statement either:

print("The cheapest option for you would be {} with {}.".format(cost, shipping))
(cost & shipping must be in the same order as the two {})

or

print("The cheapest option for you would be {1} with {0}.".format(shipping, cost))
(The numbers within {} indicate the index of the arguments within the format tuple to use in each.)

or

print("The cheapest option for you would be {c} with {s}.".format(c = cost, s = shipping))
(Where c & s can be any variable names)

… but not print("The cheapest option for you would be {cost} with {shipping}.".format(cost, shipping))
… that won’t work (for either input.)