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

Done improperly being added to the list

I'm early in the video I'm working on, but I'm having an issue that I can't figure out.

Here is my code:

list = []
item = ''

while item != 'DONE':
    item = input("What item do you need to shop for?\n")

    if item == 'SHOW':
        print(list)
    else:
        list.append(item) 

print(list)

When I put 'DONE' it stops the loop and shows me the list, as it should, but it also adds itself as the last item, which it shouldn't be doing. I don't understand why item is 'DONE' is not causing it to skip that entire code block and go right to printing the list.

1 Answer

Hi Jenna,

The reason it still appends 'DONE' to the list, is because the while condition is only checked at the beginning of each repetition of the loop. When you enter 'DONE', it will still run the rest of the code until the loop restarts and checks the while condition again. At this point it will evaluate to False and stop the loop right there.

If you want to exit the loop while it's running, you will need to make use of the break keyword. I'm not sure which point you are at in the course, but you will be introduced to it soon.

That makes perfect sense. Thank you!