Update Stock
Part of the Logic & Flow section of Coddy's Python journey — lesson 69 of 78.
Challenge
EasyCreate a function named update_stock that takes two arguments: item (string) and quantity (int). The function should:
- Check if the item exists in the
inventorydictionary.- If it does not exist, print
"Error: Item '<item>' not found.".
- If it does not exist, print
- If the item exists, calculate the new stock by adding the
quantityto the current stock.- If the new stock is negative, print
"Error: Insufficient stock for '<item>'."and do not update. - Otherwise, update the stock in the
inventory.
- If the new stock is negative, print
- Print
"Stock for '<item>' updated successfully.".
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)
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) 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.")
add_item("Apple", 0.5, 100)
add_item("Banana", 0.2, 50)
add_item("Apple", 0.6, 30) # Should print an error
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