Check Availability
Part of the Logic & Flow section of Coddy's Python journey — lesson 70 of 78.
Challenge
EasyCreate a function named check_availability that takes one argument: item (string). The function should:
- Check if the item exists in the
inventorydictionary.- If it does not exist, return
"Item not found".
- If it does not exist, return
- If the item exists, return the current stock of the item.
Add (replace) the following block of code at the bottom of your code:
add_item("Apple", 0.5, 100)
add_item("Banana", 0.2, 50)
update_stock("Apple", -20)
update_stock("Banana", 30)
print(check_availability("Apple")) # Should return 80
print(check_availability("Banana")) # Should return 80
print(check_availability("Orange")) # Should return "Item not found"Try it yourself
inventory = {}
def add_item(item, price, stock):
if item in inventory:
print(f"Error: Item '{item}' already exists.")
return
try:
inventory[item] = {"price": float(price), "stock": int(stock)}
print(f"Item '{item}' added successfully.")
except ValueError:
print("Error: Price and stock must be numeric.")
def update_stock(item, quantity):
if item not in inventory:
print(f"Error: Item '{item}' not found.")
return
try:
new_stock = inventory[item]["stock"] + int(quantity)
if new_stock < 0:
print(f"Error: Insufficient stock for '{item}'.")
else:
inventory[item]["stock"] = new_stock
print(f"Stock for '{item}' updated successfully.")
except ValueError:
print("Error: Quantity must be an integer.")
add_item("Apple", 0.5, 100)
add_item("Banana", 0.2, 50)
add_item("Apple", 0.6, 30) # Should print an error
update_stock("Apple", -20)
update_stock("Banana", 30)
update_stock("Orange", 10) # Should print an error
update_stock("Apple", -90)
print(inventory) All lessons in Logic & Flow
1Variables Exploration
ConstantsMultiple Variable AssignmentsSwapping VariablesPlaceholder VariablesRound NumbersList Casting4Contact Book Application
Display MenuAdd Contact7Sets Part 2
Mathematical Operations Part 1Mathematical Operations Part 2Recap - Treasure HuntSubsets and SupersetsIterating Over SetsRecap - Tournament Tracker2Dictionaries Part 1
What is a Dictionary?Creating a DictionaryAccessing ValuesModifying DictionariesRecap - Recipe Manager5Advanced Decision Making
Ternary OperatorMembership ChecksIdentity ChecksIndentation ErrorsRecap - Vacation Filter8Student Records Manager
Project OverviewAdd Student11Advanced Functions
Returning Multiple ValuesLambda Functions Part 1Lambda Functions Part 2Recap Challenge - Lambda SortRecursive Functions Part 1Recursive Functions Part 2Recap - Sum Nested List14Higher-Order Functions
The Map FunctionThe Filter FunctionRecap - Email ValidatorRecap - Number Processor3Dictionaries Part 2
Dictionary MethodsNested DictionariesChecking for KeysLooping Through DictionariesRecap - Frequency Counter9Advanced Data Aggregation
Using SumFinding Minimum and MaximumSorting Data EfficientlyRecap - Dictionary Sorter