Welcome to the Treehouse Community
The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.
Alex Avila8,570 Points
I used a function and if-else statement instead of a while loop.
Is it better to use a while loop instead of a function that acts like a loop with an if-else statement?
I changed the variables and strings to match the solution in the video, but this was my solution:
shopping_list =  def add_items(): new_item = input("New item: ") if new_item == "DONE": print("\n".join(shopping_list)) else: shopping_list.append(new_item) add_items() print("What should we pick up at the store?") print("Enter 'DONE' to stop adding items") add_items()
That's an interesting idea, but I believe it is better to use the while loop. I like the use of recursion (functions calling themselves) in this example. The while loop is easier, in my opinion, to read.
If you like this idea, (I certainly do), then shopping_list should be a global variable. Do this by having your first line of code being "global shopping_list" to declare a global variable named shopping_list, then assign that variable an empty list.
Here's the gist of scope: variables that are in a certain scope only exist in that scope. Global variables can be read and changed in any scope. Without the line "global shopping_list", shopping_list would only exist in the outermost part of the program, resulting in a possible traceback or logical errors. The reason is to avoid a Scope Error.