Advertisement
Guest User

Untitled

a guest
Oct 14th, 2019
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 10.32 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("**********")
  38. print()
  39.  
  40.  
  41. # Check user input is either yes or no
  42. def yes_no_check(question):
  43. error = "Please enter 'yes' or 'no'"
  44.  
  45. valid = False
  46. while not valid:
  47. response = input(question).lower()
  48.  
  49. if response == "y" or response == "yes":
  50. return ("yes")
  51. elif response == "n" or response == "no":
  52. return ("no")
  53. else:
  54. print(error)
  55.  
  56.  
  57. # unit checker function checks the unit is gm,kg,ml and sees the abbreviations for them
  58. def unit_checker():
  59. unit = not_blank("What is the unit of measurement for this item?: ",
  60. "",
  61. "no")
  62. unit_tocheck = unit.lower()
  63.  
  64. # Abbreviations lists
  65. gram = ["grams", "g", "gms", "gm", "gram", "grm", "grms"]
  66. kilogram = ["kilograms", "kg", "kgs", "kilogram", "k"]
  67. litre = ["litre", "ltr","liter", "l", "litres","ltrs", "liters", "lit"]
  68. millilitre = ["ml", "millilitre", "milliliter", "mls", "millilitres", "milliliters"]
  69. valid = False
  70. while not valid:
  71. if unit_tocheck in gram:
  72. return "gram"
  73. elif unit_tocheck in kilogram:
  74. return "kilogram"
  75. elif unit_tocheck in litre:
  76. return "litre"
  77. elif unit_tocheck in millilitre:
  78. return "millilitre"
  79. else:
  80. global not_right_unit
  81. not_right_unit = "False"
  82. break
  83.  
  84.  
  85. # checks if something is a number
  86. def num_check(question):
  87.  
  88. error = "Please enter a number."
  89.  
  90. valid = False
  91. while not valid:
  92. try:
  93. response = float(input(question))
  94. return response
  95. except ValueError:
  96. print(error)
  97.  
  98.  
  99. # function that checks if there are numbers in the input or not
  100. def not_blank(question, error_msg, num_ok):
  101. error = error_msg
  102.  
  103. valid = False
  104. while not valid:
  105. response = input(question)
  106. has_errors = ""
  107.  
  108. if num_ok != "yes":
  109. # look at each character in string and if it's a number, complain
  110. for letter in response:
  111. if letter.isdigit() == True:
  112. has_errors = "yes"
  113. error = "Please try again - numbers are not allowed in this field"
  114. break
  115. # response can't be blank
  116. if response == "" or response == " ":
  117. error = "Please type something (this can't be left blank)"
  118. print(error)
  119. continue
  120. elif has_errors != "":
  121. print(error)
  122. continue
  123. else:
  124. return response
  125.  
  126.  
  127. # main routine
  128.  
  129. # ***** Welcome / Instructions ********
  130. print("******** Welcome to the Great Comparison Calculator ********")
  131. print()
  132.  
  133. get_instructions = yes_no_check("Welcome. Is it your first time using this "
  134. "program? ")
  135.  
  136. if get_instructions.lower() == "yes":
  137. instructions()
  138. else:
  139. print()
  140.  
  141.  
  142. budget = ""
  143. minimum_amount = False
  144. while not minimum_amount:
  145. budget = num_check("What is your budget?: $")
  146. budget_too_small = "Please enter a number that is more than or equal to 10."
  147. if budget < 10: # budget must be at least $10
  148. print(budget_too_small)
  149. continue
  150. else:
  151. break
  152.  
  153. item_type = not_blank("What type of item do you want to compare? (e.g. Chocolates): ",
  154. "", # rather than having a generic error like "Blanks and numbers are not allowed"
  155. "no") # I wanted to tell the user exactly what is wrong in their code.
  156.  
  157.  
  158. # setting up conversion dictionary
  159. unit_central = {
  160. "litre": 1000,
  161. "millilitre": 1,
  162. "gram": 1,
  163. "kilogram": 1000
  164. }
  165.  
  166. # Set up empty items list
  167. items = []
  168. avg_unit_price = []
  169. # just declaring some locally assigned variables
  170. unit = ""
  171. item_cost = ""
  172. display_unit = ""
  173. item_weight = ""
  174.  
  175. # loop to ask users to enter item details
  176.  
  177. stop = ""
  178. while stop != "xxx":
  179. item = []
  180. user_keeps = ""
  181. # Ask user for item (via not blank function)
  182. item_name = not_blank("Please type in the item name (type 'xxx' to stop): ",
  183. "",
  184. "yes")
  185. # Stop looping if exit code is typed and there are more
  186. # than 2 items
  187. if item_name.lower() == "xxx" and len(items) > 1:
  188. break
  189.  
  190. elif item_name.lower() == "xxx" and len(items) < 2:
  191. print("You need at least two items in the list. "
  192. "Please add more items")
  193. continue
  194.  
  195. is_item_weight_too_small = ""
  196. while is_item_weight_too_small == "":
  197. item_weight = num_check("Please type in the item weight/volume: ")
  198. # item weight needs to be greater than 0.1
  199. if item_weight < 0.1:
  200. print("Please enter a number that is more than (or equal to) 0.1.")
  201. continue
  202. else:
  203. break
  204.  
  205. # unit should only be gms, kgs, mls and litres
  206. is_unit_false = ""
  207. while is_unit_false == "":
  208. not_right_unit = ""
  209. unit = unit_checker()
  210. if not_right_unit == "False":
  211. print("Only gms, kgs, mls and litres are allowed")
  212. else:
  213. break
  214.  
  215. # check if item cost is below $10
  216. is_item_cost_too_small = ""
  217. while is_item_cost_too_small == "":
  218. item_cost = num_check("Please type in the item cost: $")
  219. # user may want to enter non-compareble items
  220. while user_keeps == "":
  221. # item cost needs to be smaller than the budget
  222. if budget < item_cost:
  223. print("Your item cost is greater than your budget, it won't be included in the recommendation")
  224. user_keeps = "True"
  225. break
  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. else:
  231. break
  232. break
  233.  
  234. if user_keeps != "":
  235. print()
  236. continue
  237.  
  238. # this print() makes a space and this tells the user to put the next item.
  239. print()
  240.  
  241. # add item to list
  242. item.append(item_name)
  243. item.append(item_weight)
  244.  
  245. # turning everything to gram or mls
  246. make_all_units_one = False
  247. while not make_all_units_one:
  248. if unit in unit_central:
  249. multiply_by = unit_central.get(unit)
  250. item[1] = item[1] * multiply_by
  251. break
  252. # add to list
  253. item.append(item_cost)
  254. cost_per = item[2] / item[1]
  255. item.append(cost_per) # find cost per gram and add to item
  256.  
  257. # I want the first unit to be displayed as grams or millilitres
  258. # second unit to be displayed as kilograms or litres
  259. if unit.startswith("k", 0, 1):
  260. unit = unit.replace(unit, "grams")
  261. display_unit = "kilograms"
  262. elif unit.startswith("l", 0, 1):
  263. unit = unit.replace(unit, "millilitres")
  264. display_unit = "litres"
  265. elif unit.startswith("g", 0, 1):
  266. display_unit = "kilograms"
  267. unit = unit.replace(unit, "grams")
  268. elif unit.startswith("m", 0, 1):
  269. display_unit = "litres"
  270. unit = unit.replace(unit, "millilitres")
  271.  
  272. # add it to the list
  273. item.append(unit)
  274. item.append(display_unit)
  275. item.append(cost_per * 1000)
  276.  
  277. items.append(item)
  278. # looks better with a space
  279. print()
  280. print("***** Comparison Time! *****")
  281. print()
  282. # if budget has a decimal value - then show the decimal value, if not then don't
  283. if budget % 1 == 0:
  284. print("Budget is ${:.0f}".format(budget))
  285. else:
  286. print("Budget is ${:.2f}".format(budget))
  287.  
  288. print() # spaces things out -> easier to see
  289.  
  290. # sorts by least expensive to most expensive
  291. items.sort(key=lambda x: x[3],)
  292. print("**** Items by Cost <Least Expensive to Most Expensive> ****")
  293.  
  294. # Every item in items gets gets formatted and printed.
  295. for x in range(len(items)):
  296. print("{} {:.0f} {} costs ${:.2f} per {}".format(items[x][0], items[x][1], items[x][4], items[x][6],
  297. # take away the 's' e.g cost per grams should be cost per gram.
  298. items[x][5].replace('s', '')))
  299. avg_unit_price.append(items[x][6])
  300.  
  301. # Calculate Average Unit Price
  302. avg_unit_price = sum(avg_unit_price) / len(avg_unit_price)
  303.  
  304. print()
  305. print("The average unit price is ${:.2f} in {}s".format(avg_unit_price, items[0][5].replace('s', '')))
  306. print()
  307.  
  308. # Recommend
  309. print("**** Recommendations ****")
  310.  
  311. print("The cheapest item is {} {} for ${:.2f} and the most expensive item is {} {} for ${:.2f}"
  312. .format(items[0][0], item_type.replace('s', ''), items[0][2] ,items[-1][0], item_type.replace('s', ''), items[-1][2]))
  313.  
  314. print("When comparing {}, I recommend buying {} as it costs you the least and is the best value for your money."
  315. .format(item_type, items[0][0]))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement