Start learning free

LESSON 667 OF 673 · PROJECTS: OBJECT-ORIENTED

Vending Machine in Python: A Class with State

Practice Read the full explanation

Build a VendingMachine class for a machine that sells one kind of item for a fixed price. It keeps the money inserted so far (the credit), sells an item when the credit is enough, and gives the remaining credit back on request. A new object is made with VendingMachine() (no arguments).

Rules:

  • State. A new machine has credit 0 and price 150 (every item costs 150). In __init__(self), set self.credit = 0 and self.price = 150.
  • insert(self, amount) adds amount to the credit. Nothing is printed or returned.
  • select(self) tries to buy one item and returns a string:
    • If the credit is less than the price, return "Need N more", where N is the missing amount (price - credit) as a whole number, for example "Need 100 more". The credit does not change.
    • Otherwise (the credit is equal to or greater than the price, so exact payment works), subtract the price from the credit and return "Dispensing!". Any extra money stays in the credit.
  • refund(self) returns the whole credit and sets it back to 0, so asking again right away returns 0.

You start with this driver below your code:

m = VendingMachine()
m.insert(50)
print(m.select())
m.insert(150)
print(m.select())
print("Refunded: " + str(int(m.refund())))
m.insert(150)
print(m.select())
print("Refunded: " + str(int(m.refund())))
m.insert(100)
print(m.select())
print("Refunded: " + str(int(m.refund())))

Walk through it: 50 is not enough, so you see Need 100 more. After 150 more the credit is 200, so the machine dispenses and keeps 50 (200 - 150), and the refund is 50. Then 150 is exact payment: it dispenses and the refund is 0. Finally 100 is short by 50, the credit stays 100, and the refund is 100.

Expected output:

Need 100 more
Dispensing!
Refunded: 50
Dispensing!
Refunded: 0
Need 50 more
Refunded: 100

Write the missing amount as a whole number with str(int(self.price - self.credit)). Do the subtraction only when the item is dispensed, not when the credit is too low. If you forget it, the leftover credit is wrong and the refund is too big.

In the refund method, save the credit first, then reset it to 0, then return what you saved. Return the saved value, not self.credit.

class VendingMachine:
    def __init__(self):
        self.credit = 0
        self.price = 150

    def insert(self, amount):
        self.credit += amount

    def select(self):
        if self.credit < self.price:
            return "Need " + str(int(self.price - self.credit)) + " more"
        self.credit -= self.price
        return "Dispensing!"

    def refund(self):
        r = self.credit
        self.credit = 0
        return r

STEP 1 OF 15
    Ctrl + Enter to check

    PYTHON · PROJECTS: OBJECT-ORIENTED

    Vending Machine in Python, explained

    Problem overview

    You build a VendingMachine class for a machine that sells one kind of item at a fixed price. The machine keeps the money inserted so far, called the credit, sells an item when the credit is enough and gives the leftover credit back on request. A machine is created with VendingMachine(), with no arguments.

    • __init__(self) sets self.credit = 0 and self.price = 150.
    • insert(self, amount) adds amount to the credit. It prints and returns nothing.
    • select(self) tries to buy one item and returns a string. When the credit is below the price it returns "Need N more", where N is the missing amount, and leaves the credit alone. Otherwise it subtracts the price from the credit and returns "Dispensing!". Exact payment works, and extra money stays in the credit.
    • refund(self) returns the whole credit and resets it to 0.

    In the driver, 50 is inserted and select answers Need 100 more. After 150 more the credit is 200, the machine dispenses and keeps 50, and the refund is 50. Next, 150 is exact payment, so it dispenses and the refund is 0. Finally 100 is 50 short, the credit stays 100, and the refund is 100.

    Approach: state plus methods that change it

    A class bundles data with the actions on that data. Here the data is two fields, credit and price. Each machine made from the class has its own copies, so one machine's credit never touches another's. Every method gets self, the machine it works on, and reads or updates the fields through it.

    Think of each method by what it does to the state:

    • insert only changes the state: it adds to the credit.
    • select reads the state and answers with text. It changes the credit only on a successful purchase.
    • refund returns the state and then resets it.

    The key rule in select is to put the early exit first. If the credit is too low, the method returns the message straight away, before anything is subtracted. The code after the if then only runs when the credit covers the price, so it can subtract and dispense without another check.

    Step by step

    1. Declare the class VendingMachine. It is the blueprint for the machine's state and actions.
    2. Add the constructor, __init__(self). Python runs it when you write VendingMachine(), and self is the new machine.
    3. Create self.credit and start it at 0. A new machine holds no money.
    4. Create self.price and set it to 150. Every item costs the same, and the price is set once when the machine is made.
    5. Add insert(self, amount) back at the class level.
    6. Add amount to self.credit. Use += so the new money joins what is already there.
    7. Add select(self), which tries to buy one item.
    8. Check for too little money with an if that compares self.credit with self.price using <. Because the test is "less than", a credit equal to the price gets past it.
    9. Return the message inside the if: "Need ", the missing amount, " more". The missing amount is the price minus the credit, turned into a whole number with int() and then into text with str() so it can join the string. This branch changes nothing.
    10. Subtract the price from the credit, below the if and without extra indentation. The customer has paid, so the credit shrinks.
    11. Return "Dispensing!". This line is reached only when the credit covered the price.
    12. Add refund(self), which gives back the whole credit.
    13. Save the credit in r first. Once the credit is reset, the old value would be gone.
    14. Set self.credit back to 0. After a refund the machine holds no money.
    15. Return r, the money that was saved.

    The solution in Python

    class VendingMachine:
        def __init__(self):
            self.credit = 0
            self.price = 150
    
        def insert(self, amount):
            self.credit += amount
    
        def select(self):
            if self.credit < self.price:
                return "Need " + str(int(self.price - self.credit)) + " more"
            self.credit -= self.price
            return "Dispensing!"
    
        def refund(self):
            r = self.credit
            self.credit = 0
            return r
    
    m = VendingMachine()
    m.insert(50)
    print(m.select())
    m.insert(150)
    print(m.select())
    print("Refunded: " + str(int(m.refund())))
    m.insert(150)
    print(m.select())
    print("Refunded: " + str(int(m.refund())))
    m.insert(100)
    print(m.select())
    print("Refunded: " + str(int(m.refund())))
    

    Python details worth a look

    • Fields live on self. self.credit and self.price belong to one machine, and every method reaches them through self. The caller passes nothing for self: m.insert(50) hands the machine m over automatically.
    • Building the message. Joining text and numbers with + needs str(), because Python doesn't convert numbers on its own. "Need " + 100 + " more" would raise a TypeError. The int() also drops a fractional part: with 99.5 inserted, the message says Need 50 more.
    • Save, reset, return. In refund, the credit goes into r before the reset. Returning self.credit after setting it to 0 would always return 0.
    • Two return types. select returns a string and refund returns a number. That is why the driver wraps the refund in str(int(...)) before joining it to "Refunded: ", and prints the select results directly.

    What the driver prints

    Need 100 more
    Dispensing!
    Refunded: 50
    Dispensing!
    Refunded: 0
    Need 50 more
    Refunded: 100
    

    Edge cases and common mistakes

    • Exact payment. With a credit of exactly 150, select must dispense. Using <= in the check would refuse it.
    • Subtracting on a miss. The "Need N more" path must leave the credit alone. A machine holding 100 answers Need 50 more and still holds 100, so a later refund returns 100.
    • Forgetting the subtraction. Without it, a customer who inserted 400 could buy again and again, and the refund would return too much. With it, 400 buys two items (Dispensing! twice, leaving 100), and the third call answers Need 50 more.
    • A second refund. Asking again right away returns 0, because the first refund reset the credit.
    • Selling with no money. A new machine answers Need 150 more and its credit stays 0.
    • Printing instead of returning. select returns its message. The driver is the one that prints it.

    Testing

    • A new machine, select(): Need 150 more, credit 0.
    • Insert 149, select(): Need 1 more, credit still 149.
    • Insert 400, then select() three times: Dispensing! (credit 250), Dispensing! (credit 100), Need 50 more (credit 100).
    • Then refund() twice: 100 and then 0.
    Keep going with Python650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free