Why should I return the "cost" variable in this project?

In this exercise/project, I am asked to write a function to determine how much it would cost to ship a package of a certain weight using ground shipping. The instructions are as follows:

Write a function for the cost of ground shipping. This function should take one parameter, weight , and return the cost of shipping a package of that weight.

The instructions include the word “cost” written in code, which makes me believe that I should be returning a variable called “cost” - am I reading this correctly? And, if so, why is it necessary to create a variable within the function to return? It seems like more work to me. Here is the code I wrote for this project, and it worked just fine - even though I didn’t create a variable called “cost”:

def ground_shipping(weight):
  if weight <= 2:
    return 20 + (1.5 * weight)
  elif weight <= 6:
    return 20 + (3 * weight)
  elif weight <= 10:
    return 20 + (4 * weight)
    return 20 + (4.75 * weight)
1 Like

In one school of thinking, a single return is preferred to multiple returns, as you have above. You are not wrong, just using a different line of thinking.

cost = 20
if ...:
    cost += 1.5 * weight
elif ...:
    cost += ...
elif ...:
    cost += ...
else ...:
    cost += ...
return cost

Either way is fine. The above is a little more explicit, is all (and has only one return statement).


Wow! That does seem more complicated. :astonished:

Yes and no. It depends upon which line of thought one is bound to. If a teacher says, “One return only, per function” then we would just have to put it into practice. If the teacher allows multiple returns, then we’re free to choose which way we do it. Just remember, others will be reading our code and in a collaborative setting there must be standards so everyone’s work is on par and follows the same style guide.

Some say, toh mah toh, and some say, toh may toh. On our own we can do as we choose. In a team setting, we are not always going to agree but it’s best that everyone is on the same page.

1 Like

@mtf thank you so much for your response! I was thinking I had to have a return after every if statement, but what you’re saying makes complete sense.