How to Create a Shopping List Program Using Python Control Flow Statements?
Share
Condition for Shopping List Program using Python Control Flow Statement
Description: A shopping list program allows users to manage a list of items they plan to purchase. It utilizes Python's control flow statements like loops (for, while) and conditionals (if, elif, else) to add, remove, display, or clear items interactively.
Step-by-Step Process
Initialize an Empty List: Start with an empty shopping list.
Provide Options: Use a menu-driven interface to guide the user (e.g., Add, Remove, View, Clear, Exit).
Control Flow: Use a while loop to keep the program running until the user chooses to exit.Use if-elif-else to handle different menu options.
Handle User Input: Process user inputs to add, remove, or manage items.
Exit: Break the loop when the user chooses to quit.
Sample Code
def shopping_list():
shopping_list = []
while True:
print("\n--- Shopping List Menu ---")
print("1. Add Item")
print("2. Remove Item")
print("3. View List")
print("4. Clear List")
print("5. Exit")
choice = input("Enter your choice (1-5): ")
if choice == "1":
items = input("Enter the item(s) to add (separated by commas): ")
item_list = items.split(",")
for item in item_list:
shopping_list.append(item.strip())
print(f"Items '{', '.join(item_list)}' have been added to the shopping list.")
elif choice == "2":
item = input("Enter the item to remove: ")
if item in shopping_list:
shopping_list.remove(item)
print(f"'{item}' has been removed from the shopping list.")
else:
print(f"'{item}' is not in the shopping list.")
elif choice == "3":
if shopping_list:
print("\nShopping List:")
for idx, item in enumerate(shopping_list, start=1):
print(f"{idx}. {item}")
else:
print("The shopping list is empty.")
elif choice == "4":
shopping_list.clear()
print("The shopping list has been cleared.")
elif choice == "5":
print("Exiting the program. Goodbye!")
break
else:
print("Invalid choice. Please enter a number between 1 and 5.")
shopping_list()