← Back to Loops Part 2
πŸ’Ž

Loot Filter

4 of 6

Exercise 7: Loot Filter

You're looting treasure chests in a dungeon. Each item has a name and a gold value. You only want valuable items (worth 10 gold or more), and your bag can only hold 50 gold worth of loot before it's full.

Use continue to skip cheap items and break to stop when your bag is full.

loot = [("sword", 25), ("potion", 5), ("shield", 30), ("arrow", 3), ("helmet", 20), ("ring", 50)] bag_limit = 50

Expected output:

Looted sword (25 gold) - Bag: 25/50
Skipped potion (5 gold) - not valuable enough
Bag full! Looted shield but bag is now 55/50
Stopped looting - bag is full!
Total loot: 55 gold (2 items)

Requirements

  • Use a for loop to go through the loot list
  • Use continue to skip items worth less than 10 gold (print a skip message first)
  • Add valuable items to a running total
  • After adding an item, check if you've exceeded the bag limit β€” if so, print the full message and break
  • Print the final total and item count
  • No starter code β€” write the whole solution yourself!

Hints

Hint 1 β€” Unpacking tuples

Each item in the loot list is a tuple with two values. You can unpack them in the for loop:

for name, value in loot:
Hint 2 β€” Order of checks

Inside the loop:

  1. First check if value < 10 β†’ print skip message β†’ continue
  2. Add value to your bag total, increment item count
  3. Check if bag total >= bag_limit β†’ print full message β†’ break
  4. Otherwise print the normal loot message
Hint 3 β€” Watch the print order

When the bag becomes full, you print a different message than the normal loot message. You'll need an if/else after adding the item:

if bag_total >= bag_limit: print(f"Bag full! Looted {name} but bag is now {bag_total}/{bag_limit}") print("Stopped looting - bag is full!") break else: print(f"Looted {name} ({value} gold) - Bag: {bag_total}/{bag_limit}")
πŸ’»

Try it yourself

Code: Loot Filter

Loading Python runtime…
Python …
Loading...
Output
Click "Run" to execute your code...
ℹ️ About this Python environment

βœ… Standard library: heapq, collections, itertools, math, random, functools, datetime, bisect

βœ… Functions, classes, recursion, print()

❌ No file system, subprocess, OS access, or network requests

❌ No pip install (all supported modules are pre-loaded)

⏱️ 5 second execution time limit