Skip to content

Create a Shopping List

  • Project
  • 1 hint
  • 4 of 4 in this chapter

Assignment

We are going to create a shopping list program that accepts commands to add items to the list, delete items from the list, and print the whole list.

Basically, if you type add into the console, it should prompt for the item to add, if you type delete it should prompt for the item to delete, and if you type print it should print the entire list to the console.

It should look something like this when the program is run:

Text
Command: add
Item: spinach
spinach successfully added to the shopping list!

Command: add
Item: chocolate
chocolate successfully added to the shopping list!

Command: print
Shopping List:
chocolate 
spinach 

Command: delete
Item: spinach
spinach successfully deleted from the shopping list!

Command: print
Shopping List:
chocolate    
  • Use a while loop (while True: …) that repetitively runs the same program over and over again until the program is stopped
  • Check if the input is equal to a certain value, and if so, the program should do the required task (the control flow we’ve been talking about).

Hints

Hint 1h1

h1

Solution

Python
shopping_list = []

while True:
    print("") #printing an extra line to clean up the console
    user_command = input("Command: ")
    
    if user_command == "add":
        item = input("Item: ")
        shopping_list.append(item)
        print(item + " was successfully added to the shopping list!")
    
    if user_command == "delete":
        item = input("Item: ")
        shopping_list.remove(item)
        print(item + " was successfully removed from the shopping list!")
    
    if user_command == "print":
        i = 1
        print("Shopping List:")
        
        for list_item in shopping_list:
            print(str(i) + ": " + list_item)
            i = i + 1

OUTPUT

Text
Command: add
Item: spinach
spinach was successfully added to the shopping list!

Command: add
Item: chocolate
chocolate was successfully added to the shopping list!

Command: add 
Item: dog food
dog food was successfully added to the shopping list!

Command: print
Shopping List:
1: spinach
2: chocolate
3: dog food

Command: delete
Item: spinach
spinach was successfully removed from the shopping list!

Command: print
Shopping List:
1: chocolate
2: dog food    

Give the project a try first.