1 / 4

Managing Inventory with Python Dictionaries

This guide covers how to manage a simple inventory system using Python dictionaries. We will create an inventory for fruits, add quantities to existing items, and handle errors gracefully. The demonstration includes operations such as adding fruits to the inventory and displaying the current inventory status. You'll learn to handle exceptions like the KeyError when trying to access non-existent keys. Follow along to improve your coding skills in Python dictionaries and inventory management.

Télécharger la présentation

Managing Inventory with Python Dictionaries

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. CS 931: Dictionaries

  2. Dictionaries >>> inventory = {} # an empty dictionary >>> inventory['apple'] = 6 >>> inventory['orange'] = 12 >>> inventory['banana'] = 4 >>> inventory['orange'] 4 >>> inventory['coconut'] Traceback (most recent call last): File "<pyshell#49>", line 1, in <module> inventory['coconuts'] KeyError: 'coconuts' >>>

  3. Dictionaries >>> def addfruit(fruit, quant, inv): if fruit in inv: inv [fruit] += quant else: inv [fruit] = quant >>> addfruit('orange', 6) >>> addfruit('guava', 3) >>> inventory['orange'] 18 >>> inventory['guava'] 3

  4. Dictionaries iterates over inventory’s keys >>> def printinventory(): for f in inventory.iterkeys(): print f, inventory[f] >>> printinventory() orange 18 guava 3 apple 6 banana 4

More Related