The Palos Publishing Company

Follow Us On The X Platform @PalosPublishing
Categories We Write About

Create a Python-powered shopping list

Creating a Python-powered shopping list involves building a simple program where you can add, remove, view, and save your shopping items. Here’s a functional script that lets you manage a shopping list via the command line:

python
import json import os SHOPPING_LIST_FILE = 'shopping_list.json' def load_list(): if os.path.exists(SHOPPING_LIST_FILE): with open(SHOPPING_LIST_FILE, 'r') as f: return json.load(f) return [] def save_list(shopping_list): with open(SHOPPING_LIST_FILE, 'w') as f: json.dump(shopping_list, f, indent=4) def show_list(shopping_list): if not shopping_list: print("Your shopping list is empty.") else: print("Your Shopping List:") for i, item in enumerate(shopping_list, start=1): print(f"{i}. {item}") def add_item(shopping_list): item = input("Enter the item to add: ").strip() if item: shopping_list.append(item) print(f"Added '{item}' to the shopping list.") else: print("No item entered.") def remove_item(shopping_list): show_list(shopping_list) if shopping_list: try: index = int(input("Enter the number of the item to remove: ")) if 1 <= index <= len(shopping_list): removed = shopping_list.pop(index - 1) print(f"Removed '{removed}' from the shopping list.") else: print("Invalid item number.") except ValueError: print("Please enter a valid number.") def main(): shopping_list = load_list() while True: print("nOptions:") print("1. Show shopping list") print("2. Add item") print("3. Remove item") print("4. Save and exit") choice = input("Choose an option (1-4): ").strip() if choice == '1': show_list(shopping_list) elif choice == '2': add_item(shopping_list) elif choice == '3': remove_item(shopping_list) elif choice == '4': save_list(shopping_list) print("Shopping list saved. Goodbye!") break else: print("Invalid choice, please select from 1 to 4.") if __name__ == "__main__": main()

This script uses a JSON file to save the list persistently. You can add items, view the list, remove items by their number, and save the list on exit. Run the script, and follow the menu prompts to manage your shopping list.

Share this Page your favorite way: Click any app below to share.

Enter your email below to join The Palos Publishing Company Email List

We respect your email privacy

Categories We Write About