Sal's Shipping - Check Code

Please, why the cost function is reported as not defined in the end of the code below?

def ground_shipping(weight):

  if (weight <= 2):

    return weight * 1.50 + 20.00

  elif (weight > 2) and (weight <= 6):

    return weight * 3.00 + 20.00

  elif (weight > 6) and (weight <= 10):

    return weight * 4.00 +20.00

  elif (weight > 10):

    return weight * 4.75 + 20.00 


premium_ground_shipping = 125.00 

def drone_shipping(weight):

  if (weight <= 2):

    return weight * 4.50 

  elif (weight > 2) and (weight <= 6):

    return weight * 9.00 

  elif (weight > 6) and (weight <= 10):

    return weight * 12.00 

  elif (weight > 10):

    return weight * 14.25  


def cheapest_shipping_method(weight):

  ground = ground_shipping(weight)

  drone = drone_shipping

  premium = premium_ground_shipping(weight)

  if (ground < drone) and (drone < premium):

    method = "ground_shipping"

    cost = ground

  elif (drone < ground) and (ground < premium):

    method = "drone_shipping"

    cost = drone


    method = "premium_ground_shipping"

    cost = premium


  "The cheapest option available is $%.2f with %s shipping."

  % (cost, method)


Traceback (most recent call last):
File “”, line 43, in
% (cost, method)
NameError: name ‘cost’ is not defined

You must select a tag to post in this category. Please find the tag relating to the section of the course you are on E.g. loops, learn-compatibility

When you ask a question, don’t forget to include a link to the exercise or project you’re dealing with!

If you want to have the best chances of getting a useful answer quickly, make sure you follow our guidelines about how to ask a good question. That way you’ll be helping everyone – helping people to answer your question and helping others who are stuck to find the question and answer! :slight_smile:

function parameters (like cost) are local variable, they only exists within the function

Trying to access variable outside there designated scope will result in a NameError


You also need to call the last function and pass an argument through it.
(unless I missed that in the code?)


Thanks for your help!

Could, please, what a I should do in the code?

Kind regards,


Take a look at this line:


  "The cheapest option available is $%.2f with %s shipping."

  % (cost, method)

Here, you reference the variable cost, however, this print line is outside of the function cheapest_shipping_weight, where cost is only a local variable.

1 Like

The code is secondary objective. The primary objective should be to determine what you did wrong, and understand why

So you tried to access a variable outside its scope, which leaves you with two options:

change the scope of the variable
change where and when you access the variable

which of the two options do you think is right for your situation?

1 Like

I changed the position of the variable to inside the function and it worked.

1 Like