Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Functions go here
- # function that consists of all the instructions
- def instructions():
- print()
- print("******** Instructions ********")
- print()
- print("This handy program compares one item to another, it can convert between grams to kilograms and millilitres to litres. \n"
- "It also tells you what item is the best value for your money! Imagine that!.")
- print()
- print("The program will ask for your budget. \n"
- "All you need to do is put in how much you have on hand. \n"
- "Leave the rest to the program.")
- print()
- print("The program also asks for the type of item you are comparing. \n"
- "This is relatively straight forward. But here is an explanation if you are still confused: \n"
- "if you are comparing Kit-Kat with Snickers than the type of item you are comparing is Chocolates.")
- print()
- print("Then the computer will ask you for the item name. \n"
- "Going back about to the example of chocolates above, the item name will be Kit-Kat.")
- print()
- print("The program will then ask you about the weight of your item.\n"
- "e.g Kit-Kat weighs 55 grams so you put in 55. \n"
- "Then the program will ask you the unit, so you can enter grams or gm (use any abbreviation you like).")
- print()
- print("Lastly, you would be asked for the cost of the item. \n"
- "If for example Kit-Kat 55 grams costs 1.50, then you put in 1.50 \n"
- "Yup, it's as simple as that.")
- print()
- print("This process is repeated unit you put in 'xxx'. This tells the program that you have entered all the items \n"
- "you want to compare.")
- print()
- print("Then as if it were magic, the program will sort out all your items and give you a recommendation on what to buy.")
- print("**********")
- print()
- # Check user input is either yes or no
- def yes_no_check(question):
- error = "Please enter 'yes' or 'no'"
- valid = False
- while not valid:
- response = input(question).lower()
- if response == "y" or response == "yes":
- return ("yes")
- elif response == "n" or response == "no":
- return ("no")
- else:
- print(error)
- # unit checker function checks the unit is gm,kg,ml and sees the abbreviations for them
- def unit_checker():
- unit = not_blank("What is the unit of measurement for this item?: ",
- "",
- "no")
- unit_tocheck = unit.lower()
- # Abbreviations lists
- gram = ["grams", "g", "gms", "gm", "gram", "grm", "grms"]
- kilogram = ["kilograms", "kg", "kgs", "kilogram", "k"]
- litre = ["litre", "ltr","liter", "l", "litres","ltrs", "liters", "lit"]
- millilitre = ["ml", "millilitre", "milliliter", "mls", "millilitres", "milliliters"]
- valid = False
- while not valid:
- if unit_tocheck in gram:
- return "gram"
- elif unit_tocheck in kilogram:
- return "kilogram"
- elif unit_tocheck in litre:
- return "litre"
- elif unit_tocheck in millilitre:
- return "millilitre"
- else:
- global not_right_unit
- not_right_unit = "False"
- break
- # checks if something is a number
- def num_check(question):
- error = "Please enter a number."
- valid = False
- while not valid:
- try:
- response = float(input(question))
- return response
- except ValueError:
- print(error)
- # function that checks if there are numbers in the input or not
- def not_blank(question, error_msg, num_ok):
- error = error_msg
- valid = False
- while not valid:
- response = input(question)
- has_errors = ""
- if num_ok != "yes":
- # look at each character in string and if it's a number, complain
- for letter in response:
- if letter.isdigit() == True:
- has_errors = "yes"
- error = "Please try again - numbers are not allowed in this field"
- break
- # response can't be blank
- if response == "" or response == " ":
- error = "Please type something (this can't be left blank)"
- print(error)
- continue
- elif has_errors != "":
- print(error)
- continue
- else:
- return response
- # main routine
- # ***** Welcome / Instructions ********
- print("******** Welcome to the Great Comparison Calculator ********")
- print()
- get_instructions = yes_no_check("Welcome. Is it your first time using this "
- "program? ")
- if get_instructions.lower() == "yes":
- instructions()
- else:
- print()
- budget = ""
- minimum_amount = False
- while not minimum_amount:
- budget = num_check("What is your budget?: $")
- budget_too_small = "Please enter a number that is more than or equal to 10."
- if budget < 10: # budget must be at least $10
- print(budget_too_small)
- continue
- else:
- break
- item_type = not_blank("What type of item do you want to compare? (e.g. Chocolates): ",
- "", # rather than having a generic error like "Blanks and numbers are not allowed"
- "no") # I wanted to tell the user exactly what is wrong in their code.
- # setting up conversion dictionary
- unit_central = {
- "litre": 1000,
- "millilitre": 1,
- "gram": 1,
- "kilogram": 1000
- }
- # Set up empty items list
- items = []
- avg_unit_price = []
- # just declaring some locally assigned variables
- unit = ""
- item_cost = ""
- display_unit = ""
- item_weight = ""
- # loop to ask users to enter item details
- stop = ""
- while stop != "xxx":
- item = []
- user_keeps = ""
- # Ask user for item (via not blank function)
- item_name = not_blank("Please type in the item name (type 'xxx' to stop): ",
- "",
- "yes")
- # Stop looping if exit code is typed and there are more
- # than 2 items
- if item_name.lower() == "xxx" and len(items) > 1:
- break
- elif item_name.lower() == "xxx" and len(items) < 2:
- print("You need at least two items in the list. "
- "Please add more items")
- continue
- is_item_weight_too_small = ""
- while is_item_weight_too_small == "":
- item_weight = num_check("Please type in the item weight/volume: ")
- # item weight needs to be greater than 0.1
- if item_weight < 0.1:
- print("Please enter a number that is more than (or equal to) 0.1.")
- continue
- else:
- break
- # unit should only be gms, kgs, mls and litres
- is_unit_false = ""
- while is_unit_false == "":
- not_right_unit = ""
- unit = unit_checker()
- if not_right_unit == "False":
- print("Only gms, kgs, mls and litres are allowed")
- else:
- break
- # check if item cost is below $10
- is_item_cost_too_small = ""
- while is_item_cost_too_small == "":
- item_cost = num_check("Please type in the item cost: $")
- # user may want to enter non-compareble items
- while user_keeps == "":
- # item cost needs to be smaller than the budget
- if budget < item_cost:
- print("Your item cost is greater than your budget, it won't be included in the recommendation")
- user_keeps = "True"
- break
- # item cost needs to be greater than 10 cents
- if item_cost < 0.10:
- print("Please enter a number that is more than or equal to 0.1.")
- continue
- else:
- break
- break
- if user_keeps != "":
- print()
- continue
- # this print() makes a space and this tells the user to put the next item.
- print()
- # add item to list
- item.append(item_name)
- item.append(item_weight)
- # turning everything to gram or mls
- make_all_units_one = False
- while not make_all_units_one:
- if unit in unit_central:
- multiply_by = unit_central.get(unit)
- item[1] = item[1] * multiply_by
- break
- # add to list
- item.append(item_cost)
- cost_per = item[2] / item[1]
- item.append(cost_per) # find cost per gram and add to item
- # I want the first unit to be displayed as grams or millilitres
- # second unit to be displayed as kilograms or litres
- if unit.startswith("k", 0, 1):
- unit = unit.replace(unit, "grams")
- display_unit = "kilograms"
- elif unit.startswith("l", 0, 1):
- unit = unit.replace(unit, "millilitres")
- display_unit = "litres"
- elif unit.startswith("g", 0, 1):
- display_unit = "kilograms"
- unit = unit.replace(unit, "grams")
- elif unit.startswith("m", 0, 1):
- display_unit = "litres"
- unit = unit.replace(unit, "millilitres")
- # add it to the list
- item.append(unit)
- item.append(display_unit)
- item.append(cost_per * 1000)
- items.append(item)
- # looks better with a space
- print()
- print("***** Comparison Time! *****")
- print()
- # if budget has a decimal value - then show the decimal value, if not then don't
- if budget % 1 == 0:
- print("Budget is ${:.0f}".format(budget))
- else:
- print("Budget is ${:.2f}".format(budget))
- print() # spaces things out -> easier to see
- # sorts by least expensive to most expensive
- items.sort(key=lambda x: x[3],)
- print("**** Items by Cost <Least Expensive to Most Expensive> ****")
- # Every item in items gets gets formatted and printed.
- for x in range(len(items)):
- print("{} {:.0f} {} costs ${:.2f} per {}".format(items[x][0], items[x][1], items[x][4], items[x][6],
- # take away the 's' e.g cost per grams should be cost per gram.
- items[x][5].replace('s', '')))
- avg_unit_price.append(items[x][6])
- # Calculate Average Unit Price
- avg_unit_price = sum(avg_unit_price) / len(avg_unit_price)
- print()
- print("The average unit price is ${:.2f} in {}s".format(avg_unit_price, items[0][5].replace('s', '')))
- print()
- # Recommend
- print("**** Recommendations ****")
- print("The cheapest item is {} {} for ${:.2f} and the most expensive item is {} {} for ${:.2f}"
- .format(items[0][0], item_type.replace('s', ''), items[0][2] ,items[-1][0], item_type.replace('s', ''), items[-1][2]))
- print("When comparing {}, I recommend buying {} as it costs you the least and is the best value for your money."
- .format(item_type, items[0][0]))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement