import sys import random class Machine: coins = { "1/2": 1/2, "1/4": 1/4, "1/8": 1/8, "1/10": 1/10 } price = round( coins["1/%d" % random.choice([2, 4, 8, 10])] * random.randint(5, 10), 3 ) state = 0 def run(self): while self.state < self.price: print("".center(64, "-")) print("# Your balance:", self.state) print("# You need:", self.price) print("# Accepting coins:", ", ".join(self.coins.keys())) coin = self.expect_coin() self.state += coin if self.state >= self.price: print("\nOK:", self.state) if self.state > self.price: print("You overpaid by: %.3f" % (self.state - self.price)) return def expect_coin(self): coin = None while coin not in self.coins: try: coin = input("Insert coin> ") coin = coin.strip() if coin not in self.coins: print("Unsupported coin:", coin) except KeyboardInterrupt as e: print("\nGoodbye. No change, sorry.") sys.exit(0) except: continue return self.coins[coin] m = Machine() m.run()