The program offers items, has the user pay for items, gives the items, and updates the stock of each item. It seems to work more or less. I have 2 questions:
I don’t know how to exit the vending machine program after the user answers “n” to “buy something else? (y/n): “.
Is there a way to make the code simpler/better?
def vend(): a = {'item': 'choc', 'price': 1.5, 'stock': 2} b = {'item': 'pop', 'price': 1.75, 'stock': 1} c = {'item': 'chips', 'price': 2.0, 'stock': 3} d = {'item': 'gum', 'price': 0.50, 'stock': 1} e = {'item': 'mints', 'price': 0.75, 'stock': 3} items = [a, b, c, d, e] cim = 0 # cash in machine print('welcome to vending machine! n***************') # show items, prices def show(items): print('nitems available n***************') for item in items: if item.get('stock') == 0: items.remove(item) for item in items: print(item.get('item'), item.get('price')) print('***************n') # have user choose item while True: show(items) selected = input('select item: ') for item in items: if selected == item.get('item'): selected = item price = selected.get('price') while cim < price: cim = float(input('insert ' + str(price - cim) + ': ')) else: print('you got ' + selected.get('item')) selected['stock'] -= 1 cim -= price print('cash remaining: ' + str(cim)) a = input('buy something else? (y/n): ') if a == 'n': if cim != 0: print(str(cim) + ' refunded') cim = 0 print('thank you, have a nice day!n') break else: print('thank you, have a nice day!n') break else: continue vend()
Advertisement
Answer
1) I don’t know how to exit the the vending machine program after the user answers ‘n’ to ‘buy something else? (y/n): ‘.
The break statement in Python breaks out of the first for or while loop which encloses it. You are only exiting the for loop that you show. The while True condition keeps you looping forever.
However, you did something smart, you enclosed all the vending machine functionality in your vend function. If you use a return statement in place of break, you will not only exit your vend function, you will reach the end of your whole program and quit as you want.
The return statement is also used to return values from function calls, but you don’t need to do that in your case.
Also, you don’t need, and shouldn’t have, two separate exits from the function. Remove these three lines:
else: print('thank you, have a nice day!n') break
Outdent the two lines immediately above the three that you deleted, and replace break with return.
There are other improvements you could make too, but that’s a start.