You can't calculate the total cost because you aren't passing any costs around your functions. I would suggest you rearrange slightly, starting with a generic function to handle the main buying:
def buy_something(items_dict, credit):
"""Give the user their options, allow them to choose, return price."""
This gets a dictionary of items to buy, loops until the user chooses one they can afford or "none"
, then returns the price of the selected item. Note that you have a dictionary with name and price; you don't need to hard-code the prices elsewhere as you do at the moment. You could also let the user select by an item number instead of typing the whole name (look up enumerate
).
Now your drink function looks much simpler:
def buy_drink(credit):
drinks_dict = {'Water': 2, 'Mountain Dew': 1.5, 'Juice': 3}
return buy_something(drinks_dict, credit)
You can split out the other functions of the machine into:
- Take insertion of credit;
- Call
buy_
functions and subtractprice
returned fromcredit
; and - Make change from
credit
when user exits.
Something like:
def main_vend_loop():
credit = 0
while True:
print(...) # how much credit you have
ui = input(...).lower() # what to do
if ui == "insert coins":
credit += insert_coins() # credit goes up
elif ui == "get change":
return get_change(credit) # finished, give change
elif ui == "buy drink":
credit -= buy_drink(credit) # credit goes down
...
Note how the credit
is now an explicit argument, so you pass around the amount the user has and adjust it where appropriate. The "buy again" functions aren't really necessary, the user can select the same again from the "main menu".