← Back to Functions
πŸŽ’

Item Counter

4 of 6

Exercise 3: Item Counter

Your Task

In a game inventory, you might have a list like ["sword", "potion", "shield", "potion"]. Write a function that counts how many times a specific item appears.

Write a function count_item(inventory, item) that:

  • Takes a list of items and the name of an item to search for
  • Returns how many times that item appears
  • Should be case-insensitive β€” "Sword" and "sword" count as the same thing

Starter Code

def count_item(inventory, item): # Your code here pass # Test your function: backpack = ["sword", "potion", "shield", "potion", "Sword"] print(count_item(backpack, "potion")) # Should print: 2 print(count_item(backpack, "sword")) # Should print: 2 print(count_item(backpack, "bow")) # Should print: 0

Hints

Hint 1

Use a counter variable. Loop through the list and add 1 each time you find a match.

Hint 2

To compare case-insensitively, convert both strings to lowercase with .lower():

if thing.lower() == item.lower():
Solution
def count_item(inventory, item): count = 0 for thing in inventory: if thing.lower() == item.lower(): count += 1 return count
πŸ’»

Try it yourself

Code: Item Counter

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