Inside a vending machine
Buy snacks from a pretend vending machine and watch its program run line by line. Learn how variables remember things and how conditions make decisions.
- Computational thinking
- Problem solving
- Critical thinking
🧰 You will need
- 4 × Paper cups
- 1 × Piece of thin card (cereal box)
- 1 × Pencils and crayons
🥤 A box that knows how much you paid
Put in some coins, press a button, and out pops a drink, plus the right change. How does the machine remember your coins and decide what to do? Inside is a tiny computer running a program. Today you’ll look inside it.
🎮 Try it on the screen
Put in coins and buy things. The yellow lines show which part of the program just ran. The table shows the machine’s variables: its memory. Try to break it: buy something you can’t afford, empty a slot, press Cancel.
The machine’s program
when a coin goes in:credit = credit + coinwhen a button is pressed:if stock[item] == 0:show "Sold out"else if credit < price[item]:show "Add more coins"else:drop itemstock[item] = stock[item] - 1change = credit - price[item]credit = 0when the cancel button is pressed:change = creditcredit = 0
Variables (the machine’s memory)
| credit | 0 |
|---|---|
| change | 0 |
| stock | Apple: 3, Juice: 2, Crisps: 1, Water: 4 |
🛠️ Be the vending machine
- Make 4 “slots” from paper cups. Put a few small things (sweets, crayons, stickers) in each and write a price on card: 2, 3, 5, 4.
- Make coins from card worth 1, 2 and 5.
- One person is the machine, and can only follow the program below. Keep a credit score on paper.
- Another person is the customer. Buy things, ask for change, press “cancel”.
- The machine must follow these rules exactly:
- When a coin goes in: add it to credit.
- When a button is pressed: IF the slot is empty, say “sold out”. ELSE IF credit is less than the price, say “need more”. ELSE give the item, take away the price from credit, and give back the rest as change.
- Did the machine ever get stuck? Write the missing rule!
💡 What happened?
- A variable is a named box that holds a value that can change, like credit or stock.
- A condition (IF… ELSE) chooses what to do, based on the variables.
- An event (“when a coin goes in”) is something that starts a piece of the program.
Almost every app works like this: wait for an event, check some conditions, update the variables, show the result.
Did it work?