Sal's Shipping ( Why do these two codes print differently)


I am going through the topic in the python 3 classes, whilst doing the first step i wanted to add an extra constrain “if the weight >= 0 then return error”

def ground_shipping(weight):
  cost = 20.00
  if weight <=0:
    return("Package must have a weight greater than 0")

  elif weight <= 2:
   return("The cost is" + " " + str (cost*weight*1.50)+ " " + "dollars")

  elif weight <= 2 and weight <= 6:
   return("The cost is" + " " + str (cost*weight*3.00)+ " " + "dollars")

  elif weight <= 6 and weight <= 10:
    return("The cost is" + " " + str (cost*weight*4.00)+ " " + "dollars")

  elif weight >= 10: 
    return("The cost is" + " " + str (cost*weight*4.75) + " " + "dollars")


my question is why does
if weight <=0: return("Package must have a weight greater than 0")

have to be at the top as an if statement for it to run correctly

if i was to use the same statement as an elif statement at the bottom of the code it would print The cost is 0.0 dollars instead.

but when i use it as in the code above ^ it returns exactly as i want it

why ?

1 Like

Hi! Welcome to the forums!

You pose a question that is a common concern for day-to-day programming: what about my logic isn’t working (in the code)?

There’s two very common useful statements to “trace” what’s going on in your code (and therefore help you troubleshoot faster.

  • Print the variables (e.g.: weight)
  • Print the result of the conditional (e.g. print(weight <= 6 and weight <= 10) )
  • In other cases it even helps to print the type of the variables, but not in this one.

The types of things it can be easily figured out from that information is whether the problem is

  • logic
  • syntax
  • type
  • misuse of function
  • misuse of index
  • misuse of loops

or any combination of the above (and probably a few more).

This is a very handy technique that is surprisingly useful even in more complex scenarios.


toastedpitabread has provided great detail on how to troubleshoot your code, and any code. I am forever printing my variables or noting which part of a loop I’m in when trying to work through issues.

I just thought I would offer a specific answer in case you are stiff having issues. Take a look at the logic you are using for the comparisons. In the code above if the weight is 0 it will evaluate your first if as True as you note. When you move that to the bottom and change the first elif to an if won’t it also evaluate as True for a weight of 0?

if weight <= 2:
if 0 <= 2: which is True

Is there another way you could do the comparisons that would allow that first step to be moved down in the code?

1 Like