Some suggestions: I have added comments in the code where necessary. This may be improved upon, but a few points: no need to pass item
as it is asked for through user input, use return for exit, no need to run elif
or similar conditionals as the routine will leave via return
before it reaches the rest of the code:
def vending_process(): # no need to pass 'item' as this is an inpt
balance=20
vending_items={'Haribo':20 , 'Hershey':21, 'Lays':22, 'Cheetos':23, 'Pepsi':24, 'Dew':25, 'Rockstar':26, 'Monster': 27, 'Starbucks':28, 'Nescafe':29}
while balance > 0: # continue process till balance drops below 0
item=int(input("Choose your item from the vending machine! Choose -1 to abort: "))
if item==-1:
return -1 # exit (return preferable)
if item not in vending_items.values():
print("No such entry!")
return -2 # invalid item
if item == 20:
balance -= 1.5
print('You bought Haribo for 1.50! your balance is {}'.format(balance))
vending_process()
This produces
Choose your item from the vending machine! Choose -1 to abort: 20
You bought Haribo for 1.50! your balance is 18.5
Choose your item from the vending machine! Choose -1 to abort: 20
You bought Haribo for 1.50! your balance is 17.0
Choose your item from the vending machine! Choose -1 to abort: 20
You bought Haribo for 1.50! your balance is 15.5
Choose your item from the vending machine! Choose -1 to abort: 20
You bought Haribo for 1.50! your balance is 14.0
Choose your item from the vending machine! Choose -1 to abort: 20
You bought Haribo for 1.50! your balance is 12.5
Choose your item from the vending machine! Choose -1 to abort: 20
You bought Haribo for 1.50! your balance is 11.0
Choose your item from the vending machine! Choose -1 to abort: 20
You bought Haribo for 1.50! your balance is 9.5
Choose your item from the vending machine! Choose -1 to abort: 20
You bought Haribo for 1.50! your balance is 8.0
Choose your item from the vending machine! Choose -1 to abort: 20
You bought Haribo for 1.50! your balance is 6.5
Choose your item from the vending machine! Choose -1 to abort: 20
You bought Haribo for 1.50! your balance is 5.0
Choose your item from the vending machine! Choose -1 to abort: 20
You bought Haribo for 1.50! your balance is 3.5
Choose your item from the vending machine! Choose -1 to abort: 20
You bought Haribo for 1.50! your balance is 2.0
Choose your item from the vending machine! Choose -1 to abort: 20
You bought Haribo for 1.50! your balance is 0.5
Choose your item from the vending machine! Choose -1 to abort: 20
You bought Haribo for 1.50! your balance is -1.0
Next steps would be to add handling other items, maybe then passing the balance and the items dict
to the function to handle increasingly general cases.