Kodeclik Logo

Our Programs

Courses

Learn More

Schedule

Kodeclik Blog

How to create a shopping list in Python

In this blogpost, we will learn how to create a shopping list in Python. We will do this the object-oriented programming way, i.e., we will define a class called ShoppingList and we will create methods (functions) to work with objects of this class.

What does a ShoppingList contain? It must contain a list of items and for each item the number of such items you are purchasing and perhaps the unit price. For instance, you can have an entry like: (“Apple”, 5, 1.5) which means you are purchasing 5 apples at $1.5 each. If you have an entry like (“Banana”, 10, 0.5) you are purchasing 10 Bananas at 50 cents each.

How to create a shopping list in Python

Let us call “Apple”, “Banana”, i.e., the product you are buying as “items” and the quantity and unit price (i.e., 5 and $1.5) as “details”. We will create an associative array (dictionary) where the key is the items and the details is an array containing the quantity and unit price. Thus, “Apple” is a key and the value for that key will be [5, 1.5]. Similarly, “Banana” will be a key and the value for that key will be [10, 0.5].

Below is a very simple shopping list program:

class ShoppingList:
  def __init__(self, items=None):
      self.items = items if items else {}

  def print_list(self):
      for item, details in self.items.items():
          print(f"{item}: {details[0]} - \${details[1]}/unit")

# Example usage
my_list = ShoppingList()
my_list.print_list()

The above code thus defines a class called ShoppingList. This class has an init method, which is a special method in Python that is automatically called when a new instance of the class is created. The init method takes a parameter called items, which is set to None by default. Inside the init method, it checks if the items parameter is provided. If it is, it assigns the items to the self.items attribute. If not, it assigns an empty dictionary to self.items.

The class also has a method called print_list, which iterates through the items in the shopping list using a for loop. For each item, it prints the item name, the first element of the details associated with the item (presumably a description), and the second element of the details (presumably the price per unit), all formatted in a specific way.

In the example above, an instance of the ShoppingList class is created and assigned to the variable my_list. Since no items are provided, the shopping list is initialized as empty. The print_list method is then called on my_list, but since the list is empty, it doesn't print anything. If items were added to my_list, calling print_list would display each item's name, description, and price per unit in the specified format.

How to add items to your shopping list

To really check if the print_list is working as intended we need to apply it on a non-empty shopping list. For this, we need to add some entries to our shopping list. And how do we add entries? We need to add a method for that!

Here is an updated program:

class ShoppingList:
  def __init__(self, items=None):
      self.items = items if items else {}

  def add_item(self, name, quantity, price):
    if name in self.items:
        self.items[name][0] += quantity
    else:
        self.items[name] = [quantity, price]

  def print_list(self):
      for item, details in self.items.items():
          print(f"{item}: {details[0]} - \${details[1]}/unit")

# Example usage
my_list = ShoppingList()
my_list.print_list()
my_list.add_item("Apple", 5, 1.5)
my_list.print_list()
my_list.add_item("Banana", 10, 0.5)
my_list.print_list()

Note that we create an empty shopping list as before and then we are calling the new method “add_item” twice, once to add Apples and once to add Bananas. How does add_item() work? Let us look inside it!

In the add_item method of the ShoppingList class, a new item is added to the shopping list or the quantity of an existing item is updated. The method takes three parameters: name (the name of the item), quantity (the quantity to be added), and price (the price per unit of the item). It first checks if the item already exists in the shopping list by looking up its name in the items dictionary. If the item is found, the quantity and price are updated by adding the new quantity to the existing quantity. If the item is not found, a new entry is created in the items dictionary with the item's name as the key and a list containing the quantity and price as the value.

For example, when you call add_item("Apple", 5, 1.5), it checks if "Apple" is already in the shopping list. If it's not, a new entry is created with "Apple" as the key and [5, 1.5] as the value. If "Apple" is already in the list, the quantity is updated to be the existing quantity plus 5. This approach allows for easy management of items in the shopping list and ensures that items with the same name are consolidated with their respective quantities and prices.

The output of the program will be:

Apple: 5 - $1.5/unit
Apple: 5 - $1.5/unit
Banana: 10 - $0.5/unit

Why is Apple printed twice? This is because we print it once after adding just apples, and then we print the full shopping list again after adding bananas, thus Apple is printed again.

How to remove items from your shopping list

Let us now add a method to remove items from your shopping list. Once again the semantics of this method will be to decrease the quantity of that item from the shopping list and if the quantity drops down to zero, we can delete it entirely. Here is the updated code:

class ShoppingList:
  def __init__(self, items=None):
      self.items = items if items else {}

  def add_item(self, name, quantity, price):
    if name in self.items:
        self.items[name][0] += quantity
    else:
        self.items[name] = [quantity, price]

  def remove_item(self, name, quantity):
    if name in self.items:
        self.items[name][0] -= quantity
        if self.items[name][0] <= 0:
            del self.items[name]


  def print_list(self):
      for item, details in self.items.items():
          print(f"{item}: {details[0]} - \${details[1]}/unit")

# Example usage
my_list = ShoppingList()
my_list.add_item("Apple", 5, 1.5)
my_list.add_item("Banana", 10, 0.5)
my_list.remove_item("Banana",5)
my_list.print_list()

In the remove_item method of the ShoppingList class, an existing item is removed from the shopping list or its quantity is updated. The method takes two parameters: name (the name of the item to be removed) and quantity (the quantity to be removed from the item). It first checks if the item exists in the shopping list by looking up its name in the items dictionary. If the item is found, the quantity is updated by subtracting the specified quantity from the existing quantity. If the resulting quantity is less than or equal to 0, the item is removed from the shopping list. If the item is not found, no action is taken.

For example, when you call remove_item("Apple", 2), it checks if "Apple" is in the shopping list. If it's found and the existing quantity is greater than 2, the quantity is updated to be the existing quantity minus 2. If the resulting quantity is 0 or less, "Apple" is removed from the shopping list. This method provides a way to update item quantities and remove items from the shopping list based on user input, ensuring that the list remains accurate and up to date.

The output of the above program will be:

Apple: 5 - $1.5/unit
Banana: 5 - $0.5/unit

If you like this so far, you can add more methods to your shopping list class.

Giving discounts to shoppers

For instance, you can add a discount method that reduces the price of each item in the list by a certain percentage:

class ShoppingList:
  def __init__(self, items=None):
      self.items = items if items else {}

  def add_item(self, name, quantity, price):
    if name in self.items:
        self.items[name][0] += quantity
    else:
        self.items[name] = [quantity, price]

  def apply_discount(self, factor):
    for item in self.items:
        self.items[item][1] *= (1 - factor)

  def remove_item(self, name, quantity):
    if name in self.items:
        self.items[name][0] -= quantity
        if self.items[name][0] <= 0:
            del self.items[name]


  def print_list(self):
      for item, details in self.items.items():
          print(f"{item}: {details[0]} - \${details[1]}/unit")

# Example usage
my_list = ShoppingList()
my_list.add_item("Apple", 5, 1.5)
my_list.add_item("Banana", 10, 0.5)
my_list.remove_item("Banana",5)
my_list.print_list()

my_list.apply_discount(0.1) 
my_list.print_list()

In the above updated code, the apply_discount method takes a factor as input, which represents the discount to be applied uniformly to all items in the shopping list. It then iterates through each item in the items dictionary and reduces the price of each item by multiplying it with (1 - factor). This ensures that the discount is uniformly applied to all items in the shopping list.

The output will be:

Apple: 5 - $1.5/unit
Banana: 5 - $0.5/unit
Apple: 5 - $1.35/unit
Banana: 5 - $0.45/unit

Note that both the price of apples and the price of bananas has been reduced by the discount factor (ie 10%).

If you are enjoying this, you can enhance the functionality of the ShoppingList in many ways. For instance, you can create a method to calculate the total price of the shopping list, taking into account the quantity and price of each item. You can create a method called “Clear List”, which clears all items from the shopping list, effectively resetting it to an empty state. You can merge the current shopping list with another shopping list, combining the items and quantities. You can even sort the items in the shopping list based on their names or prices. The possibilities are endless! Try them out and write to us!

Learn more about Python dictionaries by starting from our blogpost on how to initialize dictionaries. Also learn how to update Python dictionaries.

Want to learn Python with us? Sign up for 1:1 or small group classes.

Kodeclik sidebar newsletter

Join our mailing list

Subscribe to get updates about our classes, camps, coupons, and more.

About

Kodeclik is an online coding academy for kids and teens to learn real world programming. Kids are introduced to coding in a fun and exciting way and are challeged to higher levels with engaging, high quality content.

Copyright @ Kodeclik 2024. All rights reserved.