Control Flow Sal's Shipping

https://www.codecademy.com/paths/computer-science/tracks/cspath-flow-data-iteration/modules/dspath-control-flow/projects/sals-shipping

I keep messing up on the checks by running the function first and then printing.
ground_shipping(8.5)
print(ground_shipping)
it returns
<function drone_shipping at 0x10ee74710>
When I do it the proper way
print(drone_shipping(1.5))
it returns the function fine. It even returns an answer with two decimal places.

I guess I am missing the concept here about order. Why can’t I run the function and then print rather than print the function? I can accept the “That’s just the way it works” answer but would like to know why.

Any and all help appreciated.

The distinction here is printing the function itself vs. printing the result of calling the function. The expression ground_shipping(8.5) calls (or invokes) the function named ground_shipping, passing in the value 8.5 for the function to use in its calculation.

However, when you use ground_shipping(8.5) all alone, the result that the function returns is “lost” because you’re not doing anything with the returned value, such as saving it to a variable or printing it out.

Further, the expression print(ground_shipping) simply prints the function (more specifically, the reference to the function’s location in memory), but does not call (invoke) the function. To call the function, as shown above, you must append a matching pair of parentheses ((...)) with appropriate argument values in between.

To capture the result of calling the function, and then print that result, you might do something like so:

shipping_cost = ground_shipping(8.5)
print(shipping_cost)

where shipping_cost is assigned the result of the calculation that calling ground_shipping with an argument of 8.5 produces.

If you don’t need to save the result for later, then you can simply do this:

print(ground_shipping(8.5))

That will call ground_shipping with an argument of 8.5, and then it will call print with the result of that call to ground_shipping.

As an aside, use triple backticks above and below a block of code in order to format it for easier reading.

3 Likes

That was what I suspected, but couldn’t articulate. Good explanation. Thanks for taking the time to answer.