![]() |
Vending Machine Program: Problem with variables - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Vending Machine Program: Problem with variables (/thread-3625.html) |
Vending Machine Program: Problem with variables - icabero0225 - Jun-08-2017 I'm trying to make a simple vending machine program. Running this program gives me this error:
global total_cost, total_insert total_cost=0 total_insert=0 float(total_cost) float(total_insert) def insertp25(): total_insert += total_insert + 0.25 print(total_insert) insertp25() insertp25()What can I do? I made the variables global yet nothing seems to work. RE: Vending Machine Program: Problem with variables - wavic - Jun-08-2017 global statement is for use in a function to reference to a global variable not local RE: Vending Machine Program: Problem with variables - buran - Jun-08-2017 to elaborate further on what wavic said, here is how it should be total_insert=0.0 def insertp25(): global total_insert total_insert += 0.25 print(total_insert) insertp25() insertp25()note that your line 8 is incorrect. it should be either like in my code above (line 5) or like this total_insert = total_insert + 0.25note that using globals is considered bad programming practice. you should pass arguments to functions instead. total_insert=0.0 def insertp25(total): total += 0.25 print(total) return total total_insert = insertp25(total_insert) total_insert = insertp25(total_insert)That said, it's obvious that using function is somewhat redundant. It only complicates the code. In a more advanced approach you would use class, e.g. class VendingMachine(object): accepted_coins = (0.25, 0.50, 1.00, 2.00) drinks = {'coffee':0.50, 'tee':1.00} def __init__(self): self.total = 0.00 def insert_coin(self, coin): if float(coin) not in self.accepted_coins: print('The machine accepts only: {}.'.format(self.accepted_coins), end=' ') else: self.total += coin print('Total of {:.2f} in the machine'.format(self.total)) def buy(self, buy_drink): buy_drink = buy_drink.lower() if buy_drink not in self.drinks: print("We don't have {}. You can buy only:".format(buy_drink)) for drink, price in sorted(self.drinks.items()): print('{} for {:.2f}'.format(drink, price)) elif self.total < self.drinks[buy_drink]: print('Not enough money in the machine. Please insert {:.2f} more'.format(self.drinks[buy_drink] - self.total)) else: self.total -= self.drinks[buy_drink] print('Take your {}. Total of {:.2f} in the machine'.format(buy_drink, self.total)) vm = VendingMachine() vm.insert_coin(0.25) vm.insert_coin(0.25) vm.insert_coin(0.75) vm.insert_coin(1.0) vm.buy('tee') vm.buy('tee') vm.insert_coin(0.50) vm.buy('tee') vm.buy('juice') Of course, this is only sample implementation.
|