Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Mark Libario
9,003 PointsShopping List with: SHOW, HELP, DELETE, and DONE. But How do I add SAVE?
shopping_list = []
def show_help():
print("Please type HELP to see controls.")
print("Please type DONE if you want to quit.")
print("Please type SHOW to see your current list.")
print("Please type DEL to delete the last item on the list.")
def show_list():
number = 1
print("Here are all your shopping list: ")
for item in shopping_list:
print("{}. {}".format(number, item))
number += 1
def delete_item():
shopping_list.pop(-1)
print("Today is your grocery day!")
print("Please list all the items that you are planning to buy today")
print("Once you are done, please type 'DONE' to quit.")
while True:
list_input = input("> ")
if list_input.upper() == "DONE":
show_list()
break
elif list_input == "":
print("That is not a valid item on the list. Please try again")
continue
elif list_input.upper() == "HELP":
show_help()
continue
elif list_input.upper() == "SHOW":
show_list()
continue
elif list_input.upper() == "DEL":
print("You have deleted: {}.".format(shopping_list[-1]))
shopping_list.pop(-1)
continue
shopping_list.append(list_input)
This is what I did so far. Is there anything else I can do to make it better or I am already on the right track? :) I dont know how to start working on a "SAVE" and "LOAD" functionality. How would I make it in a way that if a number was inputted, it will throw an exception like what I did with an empty string?
2 Answers
Stuart McIntosh
Python Web Development Techdegree Graduate 22,874 PointsHi there, are you looking to save to and read from a file? If yes then you would do that at the start and as you quit the script. Have you reached that yet in your learning? On raising an exception as there are quite a lot of permutations you might want to do something like:
MENU_ITEMS = ["DONE", "HELP", "SHOW", "DEL"]
# in your loop you can then do the following
if list_input.upper() == MENU_ITEMS[1]:
show_help()
break
# and your exception would be along the lines of to capture all bad entries
elif list_input.upper() not in MENU_ITEMS:
print("That is not a valid item on the list. Please try again")
continue
Hope that is helpful, let me know if you want help with saving and loading from a file.
Stuart McIntosh
Python Web Development Techdegree Graduate 22,874 PointsHi there Mark, I did this to hopefully show how to load and save from a file. I will let you complete all the needed functionality... Please let me know if this makes sense. p.s. I didnt do any testing of this so it might be buggy!!!
import os
import sys
import time
# constants
BANNER = '''
____ _ _ _ _ _
/ ___|| |__ ___ _ __ _ __ (_)_ __ __ _ | | (_)___| |_
\___ \| '_ \ / _ \| '_ \| '_ \| | '_ \ / _` | | | | / __| __|
___) | | | | (_) | |_) | |_) | | | | | (_| | | |___| \__ \ |_
|____/|_| |_|\___/| .__/| .__/|_|_| |_|\__, | |_____|_|___/\__|
'''
# global variable
shopping_list = []
def display_banner():
print('\n' + BANNER + '\n')
def clear_screen():
print("\033c", end="")
def read_file():
try:
with open('sh_list.txt', 'r+') as f: # try and open the file
contents = f.readlines() # read all the lines into a list
contents = [x.strip() for x in contents] # I turn the list into a set to remove duplicates
for line in set(contents): # create the shopping_list to be used throughout app
shopping_list.append(line)
except FileNotFoundError: # if file does not exist create it
f = open('sh_list.txt', 'w+')
f.close() # close the file
def view_list():
clear_screen()
print('\n\n Here are the items in the shopping list!\n')
if len(shopping_list) > 0:
for item in shopping_list:
print('{}'.format(item))
input('\nPress enter to return to main menu')
else:
print('\nThe shopping list is empty, returning to main menu')
time.sleep(1.5)
return
def add_item():
while True:
item = input('\nPlease enter an item to add to the the shopping list : ')
if item is not None:
shopping_list.append(item)
ans = input('\nDo you want to add another item [Y/n] : ')
if ans.upper() == 'Y':
continue
else:
return
else:
print('\n\nYou did not enter an item!')
continue
def update_file():
sh_file = open('sh_list.txt', 'a') # open the file in append mode
for item in shopping_list: # for each item in the list
sh_file.write(item + '\n') # write to the file
sh_file.close # close the file
def main_loop():
while True:
clear_screen()
display_banner()
print('1. View list : V')
print('2. Add Item : A')
print('3. Quit : Q')
option = input('\n\nPlease select menu option [V,A,Q] : ')
if option.upper().strip() == 'V':
view_list()
elif option.upper().strip() == 'A':
add_item()
elif option.upper().strip() == 'Q':
clear_screen()
print('\n\n Leaving shopping list app - Bye!\n\n\n')
update_file()
sys.exit()
else:
input('\n\nYou must choose either option V,A or Q')
continue
if __name__ == '__main__':
read_file()
main_loop()
The docs: https://docs.python.org/3/tutorial/inputoutput.html
Mark Libario
9,003 PointsMark Libario
9,003 PointsThanks Stuart. Regarding the save and load function, I dont even know how to start it lol. Any documentation that can lead me to it so I can work on it? Cant seem to find it in the main Python docs..