HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonModerate

Shipping charge based on weight

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
chargeweightbasedshipping

Problem

The program here is simply supposed to tell you the shipping charge based off of the weight of the package. I am just wondering if there is any further way to concise it? At the moment, I do not think it can go any further than that. The only place where I'm unsure whether I could improve it, could be Booleans. Possibly use a while statement?

def main():

    weight = eval(input("Please enter the weight of the package: "))

    rate = 0

    if weight  2 and weight  5 and weight  10:
        rate += 5.55

    charge = rate * weight

    print("The shipping charge is: $%s" % charge)

print(main())

Solution

You are checking much more than you need to. Consider the first two cases:

if weight  2 and weight <= 5:
    # B


If weight 2. Thus, that check is redundant and can be reduced to simply weight <= 5.

The whole body can become:

if weight <= 2:
    rate += 1.25
elif weight <= 5:
    rate += 2.35
elif weight <= 10:
    rate += 4.05
else:
    rate += 5.55


Which isn't just less code, it's easier to reason about since all your bounds are visually in the same column.

Code Snippets

if weight <= 2:
    # A
elif weight > 2 and weight <= 5:
    # B
if weight <= 2:
    rate += 1.25
elif weight <= 5:
    rate += 2.35
elif weight <= 10:
    rate += 4.05
else:
    rate += 5.55

Context

StackExchange Code Review Q#109123, answer score: 11

Revisions (0)

No revisions yet.