Skip to content

Instantly share code, notes, and snippets.

@gsinclair
Created March 17, 2019 05:08
Show Gist options
  • Save gsinclair/66fa7095700049a08db08c20b9ed8244 to your computer and use it in GitHub Desktop.
Save gsinclair/66fa7095700049a08db08c20b9ed8244 to your computer and use it in GitHub Desktop.
import math
# Gets user input.
# Returns length, width, height and weight.
# The values are NOT validated.
def collect_input():
l = float(input("Enter length (cm): "))
w = float(input("Enter width (cm): "))
h = float(input("Enter height (cm): "))
weight = float(input("Enter weight (kg): "))
return (l,w,h,weight)
# Pass in: length, width, height, weight
# The function returns True if the values are valid and False otherwise.
# If any values are invalid, an error message is printed.
# There may be multiple messages printed.
def validate(l, w, h, weight):
# Find out if values are valid and print relevant error messages.
valid = True
if l <= 0 or w <= 0 or h <= 0 or weight <= 0:
print("All dimensions must be positive")
valid = False
if l > 80 or w > 80 or h > 80:
print("Length, width, height must be no more than 80cm")
valid = False
if l + w + h > 200:
print("Sum of dimensions must not exceed 200cm")
valid = False
if weight < 1.0:
print("Underweight")
valid = False
if weight > 10.0:
print("Overweight")
valid = False
return valid
# Calculates the cost of a parcel based on its weight.
# Up to 5kg is a flat $4.00.
# After that the customer is charged $0.10 for every extra 100g.
def cost_of_parcel(weight):
# We assume the weight is valid.
if weight <= 5:
return 4.00
else:
extra_weight = weight - 5
number_of_hundred_grams = math.ceil(extra_weight * 10)
return 4.00 + (0.10 * number_of_hundred_grams)
def run():
n = int(input("How many parcels? "))
num_valid = 0
num_invalid = 0
total_cost = 0
for i in range(1,n+1):
print("")
print("Input details for parcel number", i)
l, w, h, weight = collect_input()
valid = validate(l, w, h, weight)
if valid == True:
num_valid = num_valid + 1
cost = cost_of_parcel(weight)
total_cost = total_cost + cost
print("Parcel is valid")
print("Cost of parcel: $", cost)
else:
print("Parcel is invalid for the above reason(s)")
num_invalid = num_invalid + 1
# Task 2: print report on #valid and #invalid
print("")
print("Number of valid parcels: ", num_valid)
print("Number of invalid parcels:", num_invalid)
# Task 3: print the total cost
print("")
print("The total cost of the parcels is: $" + str(total_cost))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment