The full text of this chapter, to read or revisit. To practise, do the exercises.
Exercise 1 — Opening the Shop
Welcome to the Trading Post! Set up your shop.
- Create a shop dictionary with items and prices: potion costs 50, codeball costs 100, revive costs 150, rare_candy costs 200
- Display all shop items and prices
Exercise 2 — First Purchase
Time to buy your first item! Check if you can afford it.
- Create coins variable with 300
- Create empty inventory dictionary
- Check if you can afford a codeball (price: 100)
- If yes: subtract coins and add codeball to inventory
- Display coins left and inventory
Starter code
shop = {"potion": 50, "codeball": 100, "revive": 150, "rare_candy": 200}
Exercise 3 — Buying Spree
Hummm, your next fight is going to be tough, buy as many potions as you can afford!
- Loop while you can afford a potion (price: 50)
- Each iteration: subtract coins and add potion to inventory
- Display coins left and inventory
Starter code
shop = {"potion": 50, "codeball": 100, "revive": 150, "rare_candy": 200}
coins = 200
inventory = {"codeball": 1}
item_to_buy = "potion"
price = shop[item_to_buy]
if coins >= price:
coins -= price
inventory[item_to_buy] = inventory.get(item_to_buy, 0) + 1
print(f"Coins left: {coins}")
print(f"Inventory: {inventory}")
Exercise 4 — Selling Back
You changed your mind, it's no good to spend all your money, keep some of it. Sell one codeball back to the shop.
- Check if codeball is in inventory and quantity is greater than 0
- If yes: add half the shop price to coins (100 // 2 = 50)
- Decrease codeball quantity in inventory by 1
- Display coins and inventory
Starter code
shop = {"potion": 50, "codeball": 100, "revive": 150, "rare_candy": 200}
coins = 0
inventory = {"codeball": 1, "potion": 4}