Add Item
Part of the Logic & Flow section of Coddy's Python journey — lesson 68 of 78.
Challenge
EasyCreate a function named add_item that takes three arguments: item (string), price (float), and stock (int). The function should:
- Check if the item already exists in the
inventorydictionary.- If it does, print
"Error: Item '<item>' already exists.".
- If it does, print
- If the item does not exist, add it to the
inventorywith the provided price and stock.- Store the price as a float and the stock as an integer.
- Print
"Item '<item>' added 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
print(inventory) Try it yourself
inventory = {}
print(inventory) # Should output: {}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