Question

I am a beginner in Python and I am doing a vending machine program. I checked other codes here to get the answer I want but they are a little different than mine. In my program I take the user a step by step. I tried different approaches to get the total to add up and also compare the total to the amount entered to see if the user can by more products or not but I couldn't get it to work. Help is MUCH appreciated.. And also if anyone has any suggestions to improve my code please let me know.. Here's my code:

main_menu = ["Drinks", "Chips"] 
drinks_dict = {'Water':2, 'Mountain Deo':1.5, 'Juice':3} 
chips_dict = {'Pringles':7, 'Popi Snack':0.5, 'Sahar':1}
total = 0

def main_menu_func():
    print(main_menu)
    x = str(input("Choose the category you want. Type NONE to finish."))
    if( x == 'drinks'):
        print(drinks_func())
    elif ( x == 'chips'):
        print(chips_func())
    else:
        print("Please pick up your items and don't forget your change.")
        print(change_func())

def another_drink():
    x = (input("Do you want to get another drink? Type YES or NO: "))
    if (x == 'YES'):
        print(drinks_func())
    else:
        print(main_menu_func())

def another_chips():
    x = (input("Do you want to get another chips? Type YES or NO: "))
    if (x == 'YES'):
        print(chips_func())
    else:
        print(main_menu_func())

def drinks_func():
    print(drinks_dict)
    print("Type in the drink you want. If you do not want a drink type NONE:")
    drink = str(input())
    if (drink == 'Water'):
        water_cost = 2
        ## update the total cost? 
        print(another_drink())
    elif (drink == 'Mountain Deo'):
        drink_cost = 1.5
        ## update the total cost? 
        print(another_drink())
    elif (drink == 'Juice'):
        drink_cost = 3
        ## update the total cost? 
        print(another_drink())
    elif (drink == 'NONE'):
        print(main_menu_func())
    else:
        print("Please enter a valid response")
        print(drinks_func())

def chips_func():
    print(chips_dict)
    print("Please type in the chips you want")
    chips = str(input())
    if(chips == 'Pringles'):
        chips_cost = 7
        ## update the total cost? 
        print (another_chips())
    elif(chips == 'Popi Snack'):
        chips_cost = 0.5
        ## update the total cost? 
        print(another_chips())
    elif(chips == 'Sahar'):
        chips_cost = 1
        ## update the total cost? 
        print(another_chips())
    else:
        print("The response you entered isn't valid. Try again.")
        print(chips_func())

def change_func():
        print("Thank you for buying from us.")
        ## update the total cost
        change = coins - total
        print("You paid", coins, "and you bought with", str(total), ". Your change is: ", (change))


print('Welcome to the vending machine. The maximum number of coins you can enter is 3.')
coins = (float(input('Please enter your coins: ')))

coin_type = (str(input('Are your coins AEDs? Please type YES or NO: ')))
if (coin_type == "YES"): 
    print("You entered", str(coins), "Dirhams. Please select the category you want.")
    print(main_menu)
    print("Please type in the category you want:")
    category_selection = str(input())
    if(category_selection == 'Drinks'):
        print(drinks_func())
    elif(category_selection == 'Chips'):
        print(chips_func())
    else:
        print("Invalid response.")


#total = (drink_cost + chips_cost + candy_cost)

else:         
    print('We only accept AED.')
Was it helpful?

Solution

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:

  1. Take insertion of credit;
  2. Call buy_ functions and subtract price returned from credit; and
  3. 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".

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top