Advertisement
Guest User

Untitled

a guest
Oct 23rd, 2019
108
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 11.86 KB | None | 0 0
  1. # Functions go here
  2.  
  3.  
  4. # function that consists of all the instructions
  5. def instructions():
  6. print()
  7. print("******** Instructions ********")
  8. print()
  9. print("This handy program compares one item to another, it can convert between grams to kilograms and millilitres to litres. \n"
  10. "It also tells you what item is the best value for your money! Imagine that!.")
  11.  
  12. print()
  13. print("The program will ask for your budget. \n"
  14. "All you need to do is put in how much you have on hand. \n"
  15. "Leave the rest to the program.")
  16.  
  17. print()
  18. print("The program also asks for the type of item you are comparing. \n"
  19. "This is relatively straight forward. But here is an explanation if you are still confused: \n"
  20. "if you are comparing Kit-Kat with Snickers than the type of item you are comparing is Chocolates.")
  21. print()
  22. print("Then the computer will ask you for the item name. \n"
  23. "Going back about to the example of chocolates above, the item name will be Kit-Kat.")
  24. print()
  25. print("The program will then ask you about the weight of your item.\n"
  26. "e.g Kit-Kat weighs 55 grams so you put in 55. \n"
  27. "Then the program will ask you the unit, so you can enter grams or gm (use any abbreviation you like).")
  28. print()
  29. print("Lastly, you would be asked for the cost of the item. \n"
  30. "If for example Kit-Kat 55 grams costs 1.50, then you put in 1.50 \n"
  31. "Yup, it's as simple as that.")
  32. print()
  33. print("This process is repeated unit you put in 'xxx'. This tells the program that you have entered all the items \n"
  34. "you want to compare.")
  35. print()
  36. print("Then as if it were magic, the program will sort out all your items and give you a recommendation on what to buy.")
  37. print("The sort is from most expensive to least expensive, however if two items have the same unit price then the sort is the order you entered them")
  38. print("**********")
  39. print()
  40.  
  41.  
  42. # Check user input is either yes or no
  43. def yes_no_check(question):
  44. error = "Please enter 'yes' or 'no'"
  45.  
  46. valid = False
  47. while not valid:
  48. response = input(question).lower()
  49.  
  50. if response == "y" or response == "yes":
  51. return ("yes")
  52. elif response == "n" or response == "no":
  53. return ("no")
  54. else:
  55. print(error)
  56.  
  57.  
  58. # unit checker function checks the unit is gm,kg,ml and sees the abbreviations for them
  59. def unit_checker():
  60. unit = not_blank("What is the unit of measurement for this item?: ",
  61. "",
  62. "no")
  63. unit_tocheck = unit.lower()
  64.  
  65. # Abbreviations lists
  66. gram = ["grams", "g", "gms", "gm", "gram", "grm", "grms"]
  67. kilogram = ["kilograms", "kg", "kgs", "kilogram", "k"]
  68. litre = ["litre", "ltr","liter", "l", "litres","ltrs", "liters", "lit"]
  69. millilitre = ["ml", "millilitre", "milliliter", "mls", "millilitres", "milliliters"]
  70. valid = False
  71. while not valid:
  72. if unit_tocheck in gram:
  73. return "gram"
  74. elif unit_tocheck in kilogram:
  75. return "kilogram"
  76. elif unit_tocheck in litre:
  77. return "litre"
  78. elif unit_tocheck in millilitre:
  79. return "millilitre"
  80. else:
  81. global not_right_unit
  82. not_right_unit = "False"
  83. break
  84.  
  85.  
  86. # checks if something is a number
  87. def num_check(question):
  88.  
  89. error = "Please enter a number."
  90.  
  91. valid = False
  92. while not valid:
  93. try:
  94. response = float(input(question))
  95. return response
  96. except ValueError:
  97. print(error)
  98.  
  99.  
  100. # function that checks if there are numbers in the input or not
  101. def not_blank(question, error_msg, num_ok):
  102. error = error_msg
  103.  
  104. valid = False
  105. while not valid:
  106. response = input(question)
  107. has_errors = ""
  108.  
  109. if num_ok != "yes":
  110. # look at each character in string and if it's a number, complain
  111. for letter in response:
  112. if letter.isdigit() == True:
  113. has_errors = "yes"
  114. error = "Please try again - numbers are not allowed in this field"
  115. break
  116. # response can't be blank
  117. if response == "" or response == " ":
  118. error = "Please type something (this can't be left blank)"
  119. print(error)
  120. continue
  121. elif has_errors != "":
  122. print(error)
  123. continue
  124. else:
  125. return response
  126.  
  127.  
  128. # main routine
  129.  
  130. # ***** Welcome / Instructions ********
  131. print("******** Welcome to the Great Comparison Calculator ********")
  132. print()
  133.  
  134. get_instructions = yes_no_check("Welcome. Is it your first time using this "
  135. "program? ")
  136.  
  137. if get_instructions.lower() == "yes":
  138. instructions()
  139. else:
  140. print()
  141.  
  142.  
  143. budget = ""
  144. minimum_amount = False
  145. while not minimum_amount:
  146. budget = num_check("What is your budget?: $")
  147. budget_too_small = "Please enter a number that is more than or equal to 10."
  148. if budget < 10: # budget must be at least $10
  149. print(budget_too_small)
  150. continue
  151. else:
  152. break
  153.  
  154. item_type = not_blank("What type of item do you want to compare? (e.g. Chocolates): ",
  155. "", # rather than having a generic error like "Blanks and numbers are not allowed"
  156. "no") # I wanted to tell the user exactly what is wrong in their code.
  157.  
  158.  
  159. # setting up conversion dictionary
  160. unit_central = {
  161. "litre": 1000,
  162. "millilitre": 1,
  163. "gram": 1,
  164. "kilogram": 1000
  165. }
  166.  
  167. # Set up empty items list
  168. items = []
  169. # Empty list for calculating unit prices
  170. avg_unit_price = []
  171. # List for checking if the items being compared are of the same unit
  172. is_unit_same = []
  173. # List for cost for items that had the same unit price
  174. is_cost_same = []
  175.  
  176. # just declaring some locally assigned variables
  177. unit = ""
  178. item_cost = ""
  179. display_unit = ""
  180. item_weight = ""
  181. over_budget_item = []
  182. # loop to ask users to enter item details
  183.  
  184. stop = ""
  185. while stop != "xxx":
  186. item = []
  187. user_keeps = ""
  188. # Ask user for item (via not blank function)
  189. item_name = not_blank("Please type in the item name (type 'xxx' to stop): ",
  190. "",
  191. "yes")
  192. # Stop looping if exit code is typed and there are more
  193. # than 2 items
  194. if item_name.lower() == "xxx" and len(items) > 1:
  195. break
  196.  
  197. elif item_name.lower() == "xxx" and len(items) < 2:
  198. print("You need at least two items in the list. "
  199. "Please add more items")
  200. continue
  201.  
  202. is_item_weight_too_small = ""
  203. while is_item_weight_too_small == "":
  204. item_weight = num_check("Please type in the item weight/volume: ")
  205. # item weight needs to be greater than 0.1
  206. if item_weight < 0.1:
  207. print("Please enter a number that is more than (or equal to) 0.1.")
  208. continue
  209. else:
  210. break
  211.  
  212. # unit should only be gms, kgs, mls and litres
  213. is_unit_false = ""
  214. while is_unit_false == "":
  215. not_right_unit = ""
  216. unit = unit_checker()
  217. if not_right_unit == "False":
  218. print("Only gms, kgs, mls and litres are allowed")
  219. else:
  220. break
  221.  
  222. # check if item cost is below $10
  223. is_item_cost_too_small = ""
  224. while is_item_cost_too_small == "":
  225. item_cost = num_check("Please type in the item cost: $")
  226. # item cost needs to be greater than 10 cents
  227. if item_cost < 0.10:
  228. print("Please enter a number that is more than or equal to 0.1.")
  229. continue
  230. # user may want to enter items more than their item cost
  231. while user_keeps == "":
  232. # item cost needs to be smaller than the budget
  233. if budget < item_cost:
  234. print("Your item cost is greater than your budget, it won't be included in the recommendation")
  235. user_keeps = "True"
  236. break
  237. else:
  238. break
  239. break
  240.  
  241. # if the item cost is greater than budget reset item and ask everything again
  242. if user_keeps != "":
  243. # record the over budget item too
  244. over_budget_item.append(item_name)
  245. print()
  246. continue
  247.  
  248. # this print() makes a space and this tells the user to put the next item.
  249. print()
  250.  
  251. # add item to list
  252. item.append(item_name)
  253. item.append(item_weight)
  254.  
  255. # turning everything to gram or mls
  256. make_all_units_one = False
  257. while not make_all_units_one:
  258. if unit in unit_central:
  259. multiply_by = unit_central.get(unit)
  260. item[1] = item[1] * multiply_by
  261. break
  262. # add to list
  263. item.append(item_cost)
  264. cost_per = item[2] / item[1]
  265. item.append(cost_per) # find cost per gram and add to item
  266.  
  267. # I want the first unit to be displayed as grams or millilitres
  268. # second unit to be displayed as kilograms or litres
  269. if unit.startswith("k", 0, 1):
  270. unit = unit.replace(unit, "grams")
  271. display_unit = "kilograms"
  272. elif unit.startswith("l", 0, 1):
  273. unit = unit.replace(unit, "millilitres")
  274. display_unit = "litres"
  275. elif unit.startswith("g", 0, 1):
  276. display_unit = "kilograms"
  277. unit = unit.replace(unit, "grams")
  278. elif unit.startswith("m", 0, 1):
  279. display_unit = "litres"
  280. unit = unit.replace(unit, "millilitres")
  281.  
  282. # add it to the list
  283. item.append(unit)
  284. item.append(display_unit)
  285. item.append(cost_per * 1000)
  286.  
  287. items.append(item)
  288. # looks better with a space
  289. print()
  290. print("***** Comparison Time! *****")
  291. print()
  292. # if budget has a decimal value - then show the decimal value, if not then don't
  293. if budget % 1 == 0:
  294. print("Budget is ${:.0f}".format(budget))
  295. else:
  296. print("Budget is ${:.2f}".format(budget))
  297.  
  298. print() # spaces things out -> easier to see
  299.  
  300. # sorts by least expensive to most expensive
  301. items.sort(key=lambda x: x[3],)
  302. print("**** Items by Cost <Least Expensive to Most Expensive> ****")
  303.  
  304. # Every item in items gets gets formatted and printed.
  305. for x in range(len(items)):
  306. print("{} {:.0f} {} costs ${:.2f} per {}".format(items[x][0], items[x][1], items[x][4], items[x][6],
  307. # take away the 's' e.g cost per grams should be cost per gram.
  308. items[x][5].replace('s', '')))
  309. # Add the unit prices for calculating later on
  310. avg_unit_price.append(items[x][6])
  311. # Adding the per units to check if they are the same
  312. is_unit_same.append(items[x][5].replace('s', ''))
  313. # Adding all the unit prices to check if any are the same
  314. is_cost_same.append(items[x][6])
  315.  
  316. # Print if there were items that had the same unit price
  317. if len(list(dict.fromkeys(is_cost_same))) != is_cost_same:
  318. print()
  319. print("Two or more of your items had the same unit price and were sorted in the order you entered them")
  320.  
  321. # Calculate Average Unit Price
  322. avg_unit_price = sum(avg_unit_price) / len(avg_unit_price)
  323.  
  324. print()
  325. # print avg unit price
  326. print("The average unit price is ${:.2f} in {}s".format(avg_unit_price, items[0][5].replace('s', '')))
  327.  
  328. # if the measuring items are not of the same unit
  329. if len(is_unit_same) != 1:
  330. print()
  331. print("Note: to get accurate results please compare items with the same unit")
  332.  
  333. # if there is an over budget item then print the over budget item and inform user that it is is not in recommendations
  334. if over_budget_item != []:
  335. print()
  336. print("These item(s) were over you budget so they weren't included in your recommendations:")
  337. for x in range(len(over_budget_item)):
  338. print("{}".format(over_budget_item[x]))
  339. print()
  340. # Recommend
  341. print("**** Recommendations ****")
  342.  
  343. print("The cheapest item is {} {} for ${:.2f} and the most expensive item is {} {} for ${:.2f}"
  344. .format(items[0][0], item_type.replace('s', ''), items[0][2] ,items[-1][0], item_type.replace('s', ''), items[-1][2]))
  345.  
  346. print("When comparing {}, I recommend buying {} as it costs you the least and is the best value for your money."
  347. .format(item_type, items[0][0]))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement