# Sal's Shipping - Check Code

Hi,
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

print(ground_shipping(8.4))

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

print(drone_shipping(1.5))

def cheapest_shipping_method(weight):

ground = ground_shipping(weight)

drone = drone_shipping

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

method = "ground_shipping"

cost = ground

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

method = "drone_shipping"

cost = drone

else:

print(

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

% (cost, method)

)
``````

Traceback (most recent call last):
File âscript.pyâ, 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!

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

4 Likes

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

2 Likes

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

Kind regards,

Carlos

Take a look at this line:

``````
print(

"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