import sys import random class Machine: coins = sorted(set([5, 10, 20, 50, 100])) price = 5 * random.randint(4, 10) 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:", self.coins) 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:", self.state - self.price) return def expect_coin(self): coin = None while coin not in self.coins: try: coin = int(input("Insert coin> ")) 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 coin m = Machine() m.run()