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 Python Basics (2015) Shopping List App Break

Why did I have to change word to item?

The first part asked for a loop in which the answer was: for word in items: print(word) Then it asked, Oops, I forgot that I need to break out of the loop when the current item is the string "STOP". Help me add that code!

I put: for word in items: if item == 'STOP': break print(word)

now I was sure that was correct so I looked it up and I actually had to change, WORD to ITEM.

Maybe I'm missing something but I don't understand why it has to change.

2 Answers

andren
andren
28,558 Points

In a for loop the word you specify after the for keyword is the name of a variable that will exist within the loop and contain the individual items of the loop. And the word you write after the in keyword is the name of the list you are pulling items from.

So if you have a for loop like you had in your example then during the first loop Python would pull out the first item of the items variable and then assign it to the word variable. Then it would run the code. Then it would pull out the second item from the items variable and store it in the word variable and run the code again. It continues doing that until it has gone though all of the items in the items variable.

That's why you had to use print(word) to print the current item. You could have completed the task without changing word to item, but then you have to use the word variable in your if check too like this:

for word in items:
    if word == 'STOP':
        break 
    print(word)
Jason Freitas
Jason Freitas
6,716 Points

Because WORD is a variable and stores the single value from the ITEM collection. When you apply "STOP" == "ITEM", you are basically asking the program to compare the string "STOP" to a collection of values in ITEM.

oh ok.

I am completely new to this so I guess I didn't think logically.