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

Python

Shopping List Python Issue

Hi there,

When I type SHOW, HELP or DONE, it adds those items to my list before running the function. How do I fix this issue? Thanks for the help!

#Functions
#Help Function
def help():
    print("""
    These are the things you can do
    Typing DONE let's you finalize your list
    Typing SHOW let's you show your current list
    """)
#Show List Function
def show_list(shopping_list):
    print(shopping_list)
#Add items to list Function
def add_to_list(shopping_list):
    global new_item
    new_item = input("> ")
    shopping_list.append(new_item)
    print("{} Added to your list. Your list now has {} items".format(new_item,len(shopping_list)))

#Application Function
def shopping_app():
    while True:
        add_to_list(shopping_list)
        if new_item == 'SHOW':
            show_list(shopping_list)
            continue
        elif new_item == 'HELP':
             help()
             continue
        else:
            if new_item == 'DONE':
                break
    for item in shopping_list:
        print(item)
#Start of application
shopping_list = []
print("What do you need to shop for today?")
print("You can finish your list by typing DONE")
shopping_app()

I like how Peter Lodri solved this by moving add_to_list to an else statement.

while True:
        if new_item == 'SHOW':
            show_list(shopping_list)
            continue
        elif new_item == 'HELP':
             help()
             continue
        elif: #Changed to Elif
            if new_item == 'DONE':
                break
        else: #Adds item after checking it against the other test statements
             add_to_list(shopping_list)

1 Answer

Your 'add_to_list(shopping_list)' function call is in the wrong place, it runs before examinating the input, so your input first added to the list THEN comes the ifs.

I would take the input method from your add_to_list function and just put it into the while loop, like:

https://imgur.com/nfO5jVL

Sorry for the picture, haven't really figured out this board yet :D