I didn't want to post a new answer but instead make a comment, but alas, not enough reputation.

I just wanted to add to Daemon Painter's answer and say that the final total bill also isn't working as it is multiplying a dict by an int.

What could work is to initialize out of the loop the total variable as well a new total_cost variable, and place:

total_cost += total

Inside the while loop but outside the if conditions. That way the last line can just be:

print("The total price of your basket is: ", total_cost)

Edit: the code, working as intended:

    price = {"Lemonade": 1.50, "Coke": 2.00, "Fanta": 1.00, "Water": 0.50}
    shopping_basket = {}

    print("Welcome to the online drink store!\nThese are the drinks we offer\n1. Lemonade: £1.50\n2. Coke: £2.00\n3. Fanta £1.00\n4. Water: £0.50")

    buy_another_flag = 1
    total_cost, total = 0, 0

    while buy_another_flag != 0:
        option = int(input("Which drink would you like to purchase?: "))

        if option == 1:
            qnty = int(input("Enter the quantity: "))
            total = qnty * 1.50
            print("The price is: " + str(total))
        elif option == 2:
            qnty = int(input("Enter the quantity: "))
            total = qnty * 2.00
            print("The price is: " + str(total))
        elif option == 3:
            qnty = int(input("Enter the quantity: "))
            total = qnty * 1.00
            print("The price is: " + str(total))
        elif option == 4:
            qnty = int(input("Enter the quantity: "))
            total = qnty * 0.50
            print("The price is: " + str(total))

        total_cost += total

        buy_another_flag = int(input("Would you like another item? enter Yes (1) or No (0):"))
    print("The total price of your basket is: ", total_cost)
Answer from Márcio Coelho on Stack Overflow
Top answer
1 of 2
1

I didn't want to post a new answer but instead make a comment, but alas, not enough reputation.

I just wanted to add to Daemon Painter's answer and say that the final total bill also isn't working as it is multiplying a dict by an int.

What could work is to initialize out of the loop the total variable as well a new total_cost variable, and place:

total_cost += total

Inside the while loop but outside the if conditions. That way the last line can just be:

print("The total price of your basket is: ", total_cost)

Edit: the code, working as intended:

    price = {"Lemonade": 1.50, "Coke": 2.00, "Fanta": 1.00, "Water": 0.50}
    shopping_basket = {}

    print("Welcome to the online drink store!\nThese are the drinks we offer\n1. Lemonade: £1.50\n2. Coke: £2.00\n3. Fanta £1.00\n4. Water: £0.50")

    buy_another_flag = 1
    total_cost, total = 0, 0

    while buy_another_flag != 0:
        option = int(input("Which drink would you like to purchase?: "))

        if option == 1:
            qnty = int(input("Enter the quantity: "))
            total = qnty * 1.50
            print("The price is: " + str(total))
        elif option == 2:
            qnty = int(input("Enter the quantity: "))
            total = qnty * 2.00
            print("The price is: " + str(total))
        elif option == 3:
            qnty = int(input("Enter the quantity: "))
            total = qnty * 1.00
            print("The price is: " + str(total))
        elif option == 4:
            qnty = int(input("Enter the quantity: "))
            total = qnty * 0.50
            print("The price is: " + str(total))

        total_cost += total

        buy_another_flag = int(input("Would you like another item? enter Yes (1) or No (0):"))
    print("The total price of your basket is: ", total_cost)
2 of 2
0

You are looping indefinitely in the while loop.

Once you assigned option via User input here:

option = int(input("Which drink would you like to purchase?: "))

this condition is always fulfilled:

while option!= 0:

Here, you should not just print, but re-assign the option:

print("Would you like another item? enter Yes or No:")

something like this:

option = int(input("Would you like another item? enter Yes or No:"))

I hope this is pointing you in the right direction :)

(I've made assumptions on how you should have the code formatted in your original script. They might be wrong...)

🌐
GitHub
gist.github.com › richardbwest › d0365ebb89e89e7290e7cdb9cbc95530
Python Shopping List Program · GitHub
Python Shopping List Program. GitHub Gist: instantly share code, notes, and snippets.
🌐
IncludeHelp
includehelp.com › python › shop-management-system.aspx
Python program for Basic Shop Management System
January 13, 2024 - class Product: def GetProduct(self): self.__id = input("Enter Id : ") self.__name = input("Enter Name : ") self.__rate = int(input("Enter Rate : ")) self.__stock = int(input("Enter Stock : ")) def PutProduct(self): print(self.__id, self.__name, self.__rate, self.__stock) def SearchById(self, id): if self.__id == id: return True else: return False def SearchByName(self, name): if self.__name == name: return True else: return False def Sale(self): print("Sale.......") print("Quantity of Product present in stock is:", self.__stock) q=int(input("input enter qty:")) if(self.__stock>=q): amt=q*self.
🌐
Chegg
chegg.com › engineering › computer science › computer science questions and answers › grocery shopping program in python! only in intermeddiate python so try to keep the code simple as possible! not in honors class name: itemtype -------------------------- data attributes: name price class methods: __init__ allow the user to create items two ways item1 = itemtype() this should create an item
Solved Grocery Shopping program in python! only in | Chegg.com
October 6, 2015 - class ItemType: def __init__(self, name="no name", price=0.0): self.__name = name self.__price = price def __str__(self): return f"${self.__price} {self.__name}" def setName(self, name): if isinstance(name, str): self.__name = name else: print("Error: Name must be a string.") def getName(self): return self.__name def setPrice(self, price): if isinstance(price, (int, float)) and price >= 0: self.__price = price else: print("Error: Price must be a non-negative number.") def getPrice(self): return self.__price class ShoppingBasketType: def __init__(self): self.contents = [] def __str__(self): if
🌐
Learningmilestone
learningmilestone.com › post › python-program-grocery-shopping
Python Program- Grocery Shopping
December 8, 2021 - In this program, we will learn to create a python program for grocery shopping.Through this program, available items with price would be displayed to the user and the option to add items and corresponding quantities would be given until the user opts not to do further shopping.
🌐
Team Treehouse
teamtreehouse.com › community › shopping-list-app-in-python
Shopping list app in python. (Example) | Treehouse Community
December 28, 2016 - ... #make a list to hold to new ... = input("> ") #be able to quit the app if new_item == 'DONE': break #add items to shopping list shopping_list.append(new_item) #tells you your list print("Here's your list:") #prints out ...
🌐
GitHub
github.com › hemanik › Online-Store
GitHub - hemanik/Online-Store: Python Program for Online Store
Program consists of two python scripts: purchaseFinder.py Used to Search and Display all the previous purchases done by the user with the timestamp and the cost of purchase. compute-order.py Used to implement an Online Shopping Cart for a user.
Starred by 5 users
Forked by 8 users
Languages   Python 100.0% | Python 100.0%
Find elsewhere
Top answer
1 of 1
2

Code Tells You How, Comments Tell You Why?

You have tried to document your code through comments, which is great! However, comments using # are mostly intended for other programmers, and is usually reserved for explaining terse parts of the code. A common way to document your code -- which is intended for the user -- is with PEP 257 -- Docstring Conventions.

As stated in the title comments (#) should be used sparsely. First you should first strive to make your code as simple as possible to understand without relying on comments as a crutch. Only at the point where the code cannot be made easier to understand should you begin to add comments. I would further break it down into three

  1. Clarify the intent of your code through functions following the single responsibility principle
  2. Clearify what each variable do through clear variable names that follows the standard python formating conventions
  3. If the "why" is not clear through the first two points, then, and only then do we add comments.

PEP8 - Style Guide for Python Code

As to pick the lowest hanging fruits. Consistency is a key part of programming, as it greatly increases readability. It also tells a bit about the coders eye for detail. Lets' look at how you have named your global constants:

shopping_list = []

Pep8 recommends the following naming-conventions:

  • CAPITALIZED_WITH_UNDERSCORES for constants
  • UpperCamelCase for class names
  • lowercase_separated_by_underscores for other names

Now to be fair you mostly follow this standard, which is excellent! I am just pointing it out that it is smart to follow these standards.


Handling user input

Jokes aside as a rule you should never except the user to use the correct input syntax. Instead you should build in checks, exceptions to handle these errors.

What happens if I write in help? A better way is to let a function handle the user input.

def get_valid_user_input():

    options = ["add", "done", "show"]
    print(MENU)
    while True: 
        choice = input("> ").lower()
        if choice not in options:
           print(f"Ooops, you need to enter one of the valid options {options}")
        else:
           return choice

Use of functions

A part that stuck out to me was

def show_help():
    print('What should we pick up at the store?')
    print("""
  Enter 'DONE' to stop adding items.
  Enter 'HELP' for additional info.
  Enter 'SHOW' to see your shopping list
  """)

A function should be a block of organized, reusable code that is used to perform a single, related action. Now, let us go through this checklist to see whether or not this should be a function

  • Is the function called more than twice?

  • Does the function serve a single purpose?

  • Does the function perform an action?

    MENU = "What should we pick up at the store?\n\n
    Enter 'DONE' to stop adding items.\n
    Enter 'HELP' for additional info.\n
    Enter 'SHOW' to see your shopping list"
    

Since the answer to the last question was no, your function takes no input, so it could be a constant.

Note: As a general rule of thumb triple quotation marks should be reserved for docstrings and not be used for printing.


f-strings

f-strings are the new way of formating strings in Python, and you should usually use them. For instance

 print('{} was added to your shopping list!'.format(item))
 print('You have {} items on your list.'.format(len(shopping_list)))

becomes

 print(f"{item} was added to your shopping list!")
 print(f"You have {len(shopping_list)} items on your list.")

Nitpicking

  • Put the parts of your code that are the ones calling for execution behind a if __name__ == "__main__": guard. This way you can import this python module from other places if you ever want to, and the guard prevents the main code from accidentally running on every import.

A deeper look

 What should we pick up at the store?

 Enter 'DONE' to stop adding items.
 Enter 'HELP' for additional info.
 Enter 'SHOW' to see your shopping list

 >

This would be better if it read

 Enter 'DONE' to stop adding items.
 Enter 'HELP' for additional info.
 Enter 'SHOW' to see your shopping list

 What should we pick up at the store?
 >

Secondly what happens if I am unsure and type in help? I am then prompted with the same menu.

 What should we pick up at the store?

 Enter 'DONE' to stop adding items.
 Enter 'HELP' for additional info.
 Enter 'SHOW' to see your shopping list

 > HELP
 What should we pick up at the store?

 Enter 'DONE' to stop adding items.
 Enter 'HELP' for additional info.
 Enter 'SHOW' to see your shopping list

 >

Not much help there I suppose. While this is semantics, you are handling user input both as an item, which is confusing. For instance

# If the user inputs 'DONE' exit the loop
if new_item == "DONE":
    break

A better solution would be to use a different name, such as user_input and later change it to item, when it should be added to a cart. I present a slightly different way of handling this below.


My own attempt

  • I translated your comments into docstrings. They were well written and descriptive!
  • I included the if __name__ == "__main__": guard.
  • Bells and whistles I added typing hints, see PEP484.
  • Your shopping list is better structured as a simple class. This makes it easier to maintain and add functionality. (What if you wanted to remove an item from your shopping list?)
  • A more robust handling of user input. Try to write in something silly as input, what happens?
  • I've separate business logic from user interface by doing my printing in main and keeping ShoppingCart clean.
  • HELP was removed and instead a screen_clear() was added in addition to showing the menu every time.
  • A numerical menu was added as an user enchantment. Whether you think this menu style is an improvement is up to you. If you decide to keep your style, at the very least do input("> ").upper() to allow users to do add. Numerical inputs are faster to input, can be clearer, and are easier to expand to more options.
  • The menu and adding items were split into two functions (Remember, you used item for both).

code

import platform  # For getting the operating system name
import subprocess  # For executing a shell command


def clear_screen():
    """Clears the terminal screen."""

    # Clear command as function of OS
    command = "cls" if platform.system().lower() == "windows" else "clear"

    # Action
    return subprocess.call(command) == 0


MENU_OPTIONS = ["add item", "see your shopping list", "exit"]


def get_user_menu_choice() -> int:
    """Gives the user a menu to choose from"""
    low, high = 1, len(MENU_OPTIONS)
    error_msg = f"Woops, your input must be an integer in {low}...{high}\n"
    while True:
        print("Input a number from the list below:")
        for index, option in enumerate(MENU_OPTIONS):
            print(f" {1+index:>3d}: {option}")
        try:
            choice = int(input("\nPlease enter a number: "))
            if low <= choice <= high:
                return choice
        except ValueError:
            pass
        print(error_msg)


class ShoppingCart:
    def __init__(self):
        self.items = []

    def add(self, item: str):
        """Create a function that adds an item to the list"""
        if item != "":
            self.items.append(item)
        return item

    def get_items_from_user(self) -> None:
        clear_screen()
        print("\n\n\nWrite in the item you want to add to your shopping list!")
        print("[leave blank to return to menu]\n")

        item = self.add(input("> "))
        while item:

            clear_screen()
            print(f"{item} was added to your shopping list!")
            item_str = "items" if len(self.items) > 1 else "item"
            print(f"You have {len(self.items)} {item_str} in your list.")

            print("\nWrite in the item you want to add to your shopping list!")
            print("[leave blank to return to menu]\n")

            item = self.add(input("> "))

    def __str__(self) -> str:
        """Create a function to show all the items in the shopping list"""
        string = "My Shopping List:\n"
        for index, item in enumerate(self.items):
            string += f"\n{1+index:>3d}. {item}"
        return string + "\n"


def main() -> None:

    choice, add_item, display_items, exit_program = 0, 1, 2, 3

    cart = ShoppingCart()

    clear_screen()
    while choice != exit_program:
        choice = get_user_menu_choice()
        if choice == add_item:
            cart.get_items_from_user()
            clear_screen()
        elif choice == display_items:
            clear_screen()
            print(cart)


if __name__ == "__main__":
    main()
🌐
CS50
cs50.harvard.edu › python › psets › 3 › grocery
Grocery List - CS50's Introduction to Programming with Python
In a file called grocery.py, implement a program that prompts the user for items, one per line, until the user inputs control-d (which is a common way of ending one’s input to a program).
🌐
GeeksforGeeks
geeksforgeeks.org › python-maintaining-grocery-list
Python | Maintaining Grocery list | GeeksforGeeks
August 23, 2021 - Problem Statement : Make a Grocery List for super market shopping with name, price and quantity; if the list already contains an item then only update the price and quantity it should not append the item name again. Ask user his/her budget initially and minus the budget after adding a new item in the list.
🌐
Stack Overflow
stackoverflow.com › questions › 50094209 › supermarket-checkout-with-python
supermarket checkout with python - Stack Overflow
items = {'banana': {'price': 4, 'stock': 6, 'code':123 }, 'apple': {'price': 2, 'stock': 0,'code':1231 }, 'orange': {'price': 1.5, 'stock': 32,'code':1233}, 'pear': {'price': 3, 'stock': 15,'code':12335}, } bar=int(input("enter barcode:")) sum = 0 price =[] products =[] for key in items: if items[key]['code'] == int(bar): print("item found") print (key) print ("price: %s" % items[key]['price']) print ("stock: %s" % items[key]['stock']) print ("Barcode: %s" % items[key]['code']) price.append(items[key]['price']) products.append(key) print(price) print(products) print("..........................
🌐
GitHub
github.com › zbalda › shopping-organizer
GitHub - zbalda/shopping-organizer: A simple Python program to search a database for grocery items, add those items to a grocery list, and sort those items by location in store.
A simple Python program to search a database for grocery items, add those items to a grocery list, and sort those items by location in store. - zbalda/shopping-organizer
Starred by 5 users
Forked by 2 users
Languages   Python 100.0% | Python 100.0%
🌐
Python Forum
python-forum.io › thread-37566.html
Shopping cart program
#This is a shopping cart program that I am doing for school. I've managed to store the item and price. But can't get to do it the total or remove. I'm new too this and have tried many different methods and it hasten worked. If someone can help please...
Top answer
1 of 3
8

First of all well done, this is not bad for a first program :D

Good

  • Usage of functions
  • Using correct datatypes (dictionary for example)

Some Improvements in random order

  • Read PEP8, the python style guide!

  • fix your indentation

    it is standard to use 4 spaces indentation in python

  • Prettify your code for better readability

    stock={'banana':6,
    'apple':0,
    'orange':32,
    'pear':15,}
    

    this maybe subjective but that is worse to read then this

    stock={
           'banana': 6,
           'apple': 0,
           'orange': 32,
           'pear': 15
          }
    
  • uppercase can be simplified

    def uppercase(x):
        return x[0].upper()+x[1:]
    

    There is a builtin function for this

    >>> print("apple".capitalize())
    Apple
    
  • Remove tripple quotes if they are not neccesary

    name=input('''What is your name?
    ''')
    

    There is no need to let this be over 2 lines, secondly maybe add a space for better UX

    name=input('What is your name? ')
    
  • Use str.format() or f"strings" over old style formatting

    You use old style formatting alot "%s" % "somestring"

    it is better to use the new style formatting "{}".format("somestring")

    See String format best practises

  • Use a if __name__ == "__main__" guard

    It will make your script importable while also being able to run from the CLI

    if __name__ == '__main__':
        name=input('What is your name? ')
        print('Hi, {}, welcome to my fruit store. Here is the menu:'.format(name))
        menu()
        ask_fruit(117)
    
  • Avoid Magic numbers

    money=117
    

    Why 117? Because numbers can't have an explanation it is called a magic number

    Instead you can make it a global

    STARTING_MONEY = 117
    
  • Instead of empty print() use \n

  • Python doesn't really suit itself for recursion (recursion depth restrictions, memory consumption)

    def ask_fruit(money):
    fruit=input('''What fruit do you want?
    ''')
    print()
    if fruit in stock:
      if stock[fruit]>0:
        ask_amount(fruit,money)
      else:
        print('''Sorry, %ss are out of stock
        '''%(fruit))
        ask_fruit(money)
    else:
      print('''Sorry, we don\'t have that, look at the menu.
      ''')
      ask_fruit(money)
    

    Can be rewritten iterative

    def ask_fruit(money):
        while True:
            fruit=input('What fruit do you want? ')
            print()
            if fruit in stock:
                if stock[fruit] > 0:
                    ask_amount(fruit, money)
                else:
                    print('Sorry, {}s are out of stock'.format(fruit))
                    continue
            else:
                print("Sorry, we don't have that, look at the menu.")
                continue
    
2 of 3
2

Good job!

I would personally prefer to use f-strings, which are more readable.

# from
print('Price: $%s'%(prices[fruit]))
# to
print(f'Price: ${prices[fruit]}')

Using newlines ('\n') would save you from using that many prints and make your code more readable.

Four spaces (instead of two) for indentation would also show your awareness of the PEP8 style conventions

Try/Except structure (catching errors of a particular type) is more preferable and is considered as Pythonic way (refer to https://docs.python-guide.org/).

Use dict.get(). refer to: https://docs.quantifiedcode.com/python-anti-patterns/correctness/not_using_get_to_return_a_default_value_from_a_dictionary.html

🌐
w3resource
w3resource.com › python-exercises › oop › python-oop-exercise-8.php
Python OOP: Shopping cart class with item management and total calculation
July 9, 2025 - Object-oriented programming (OOP) in Python with a shopping cart class. Learn how to create methods for adding and removing items from the cart, as well as calculating the total price.
🌐
GitHub
github.com › beckskelly › python-shopping-cart
GitHub - beckskelly/python-shopping-cart: Shopping cart program in python. Command line interface project to explore the use of OOP.
Welcome to the shopping cart system. To access it you need to run the python code. You will be presented with a menu with 6 options: ... Quit Program To access the options, you must input a number between 1 and 6. Option 1 must be done first ...
Author   beckskelly
🌐
Chegg
chegg.com › homework-help › questions-and-answers › grocery-shopping-program-python-intermeddiate-python-try-keep-code-simple-possible-class-n-q8364177
Grocery Shopping Program In Python! Only In Interm... | Chegg.com
If you put a doll, a truck, and another doll, into you basket, you must print this (note the quantity number after doll) shopping basket 1) $5.29 doll (2) 2) $7.99 truck addItem This method must take a parameter of type itemType and add it to ...
🌐
GitHub
github.com › veravavan › py_shop
GitHub - veravavan/py_shop: A simple grocery shopping game for Programming in Python class.
The program will allow user to shop by adding items to the shopping cart. Possible items in the store and their prices should be displayed. The user can then type what they want to buy and how many times.
Author   veravavan
🌐
Stack Overflow
stackoverflow.com › questions › 50110231 › grocery-store-for-python
Grocery Store for Python - Stack Overflow
[Y:N]\n').lower() if i[1] > money: print('You do not have enough money for this item :(\n') break if ques == 'n': print('Sorry that you do not want that item :(') break if ques == 'y': money = money - i[1] print('\nYou now have $', money) cartList.insert(0, item) print('You have these items in your cart:\n', cartList, '\n') else: print('You entered an incorrect value :(') if ask == 'return': ret = input('What item do you want to return?\n') for i in cartList: if ret == i[0]: print(i[0], '$', i[1]) quest = input('Do you want to return this item? [Y:N]]\n').lower() else: print('This item is not in your cart!\n') print('\nThank you for shopping with us!')