Python Forum
Need help with simple shopping cart
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Need help with simple shopping cart
#3
So you now write to the file only when the user chooses choice==2. Instead, write the file when the user exits, choice ==4. Also, shoppinglist() calls itself which can lead to a recursion error. This example uses a while instead
##---------- Not Tested i.e. it is your homework

import pprint

## In the beginning, the file only contains "Shopping list:
## so no reason to write this at this time
##fp = open('/Users/dsmith/Shopping list.txt', 'w')
##fp.write("Shopping list\n")
##fp.close()
 
shoppinglistfile_list=["Shopping list"]

print()
 
def shoppinglist():
  while True:
    print('''Choose 1 to view your shopping list.
Choose 2 to add an item to your shopping list.
Choose 3 to delete an item from your shopping list.
Choose 4 to exit the program.''')
    print()
    choice = int(input("Enter your choice: "))
 
    if choice == 1:
        pprint.pprint(shoppinglistfile_list)
        print()

    elif choice == 2:
        thing_to_add = input("What would you like to add to your shopping list? ")
        shoppinglistfile_list.append(thing_to_add)
        print()
 
    elif choice == 3:
        print()
        pprint.pprint(shoppinglistfile_list)
        del_item = input("Enter item to delete ")
        print(del_item)
        shoppinglistfile_list.remove(del_item)
        print()
 
    elif choice == 4:
        print()
        print("Thank you for using ths program")
        print("--------")

        ## Python already uses the name "file"
        fp=open('/Users/dsmith/Shopping list.txt', "w")
        for rec in shoppinglistfile_list:
            fp.write("%s \n" % (rec))
        fp.close()

        return  ## exits function

    else:
        print()
        print("Please enter a valid option")
        print()
 
 
shoppinglist()
Reply


Messages In This Thread
RE: Need help with simple shopping cart - by woooee - Aug-22-2018, 04:16 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  (New to Python) Shopping List Code Farzan1 3 2,810 Oct-28-2019, 04:36 PM
Last Post: SheeppOSU

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020