Sal's Shipping 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

I am relatively new to Python and have managed to work through most of the exercises although stuck on Sals shipping where I keep getting a NameError for cost although I cant seen anything obvious I have printed my code below

def shipping_cost_ground(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 20 + (price_per_pound * weight)

print(shipping_cost_ground(8.4))

shipping_cost_premium = 125.0

def shipping_cost_drone(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 price_per_pound * weight

print(shipping_cost_drone(1.5))

def print_cheapest_shipping_method(weight):

    ground = shipping_cost_ground(weight)

    premium = shipping_cost_premium

    drone = shipping_cost_drone(weight)

    if ground < premium and ground < drone:

        method = "standard ground"

        cost = ground

    elif premium < ground and premium < drone:

        method = "premium ground"

        cost = premium

    else:

        method = "drone"

        cost = drone

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

(cost,method)

        )

print_cheapest_shipping_method(4.0)

print_cheapest_shipping_method(41.5)

the cost is defined inside the function.

Yet when you attempt to print the cheapest cost option, you do this outside/after the function. Why?

Please excuse my limited ability regarding Python, i am really struggling, what would you suggest as a better fix ? After a lot of perseverance and struggling I followed the instructional video on Codeacademy site although continually kept getting the NameError(cost) sorry to kepp repeating.

It’s hard to see without further code formatting (see this FAQ for details). Basically wrap all your code with three backticks before and after ` ` ` .
` ` `
code goes here
` ` `
Either you’re attempting to access the name cost outside the function where it’s out of scope or potentially if your print function is inside the function then double check whether the instructions say to print a value or return a value as some of the background tests may flag this up as an error.

Fantastic I will give it a go and let you know. Thanks

First you need to understand the problem. Learning to debug is really valuable

you try to access a variable (cost), which doesn’t exist. So then the first question is:

Did you define the variable?

You did, so then the second question becomes: Might there be a scope problem? What scope does cost have?