Code critique (vending machine)
This is simplistic, but just wanted to get thoughts about how this was written. I plan on expanding upon it latter.
def vending_machine(money):
'''Return a candy of a customer's choice'''
options = {'A1' : {0.75 : "Snickers"}, 'B2' : {1.00 : "Butterfinger"}}
vending_codes = options.keys() #Codes for each vending machine item
customer_choice = input("Enter a selection: ") #Represents the customers desired vending machine option
candy = options.get(customer_choice) #Retrieve candy and cost information from the code entered
if customer_choice in vending_codes:
return "Enjoy your " + candy[money]
else:
return "Try another option."
print(vending_machine(0.75))
7 comments · 100% upvoted · other discussions
This seems like a decent start to me, you could just use tuples for the (name, price) of the candy if it is going to be static or a list. then you could just candy[0] or candy[1]. If you want to keep it a dictionary I would suggest doing something like {'money': 0.75, 'name': "Snickers"}, for better clarity later on in the code. Also you can concatenate strings like that, but if it starts getting more complicated string formating works much better. So "Enjoy your {}".format(candy[name])
Ben_HH [OP] 2 points · Mar 2018
I'm thinking dictionaries might be better. I intend on having the machine reflect the total quantity of each candy after a selection. If the customer wants to make a subsequent purchase the quantities will be up to date.
If I remember correctly, tuples might not work due to their immutability if I implement the aforementioned.
Grorco 1 points · Mar 2018
So then you could do something like {'name': "Snickers", 'price': 0.75, 'quantity': 20}
Vaphell 1 points · Mar 2018
no problem with dictionaries but tuples as a representation of product type would work too. If immutability is a problem, a list is pretty much the same thing but mutable. Unpacking is a nice, convenient feature of both.