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

Conner Williams
PLUS
Conner Williams
Courses Plus Student 3,305 Points

how to solve this

Becoming incredibly frustrated with these coding challenges as it seems I cannot retain the information. How do I use a "for" loop to complete this task?

breaks.py
def loopy(items):
    # Code goes here

2 Answers

andren
andren
28,558 Points

for loops are often considered hard to understand at first, but they are actually a pretty simple construct once you wrap your head around them.

The way it works is that it takes a list you provide it, and then it pulls out an item from that list and assigns it to a variable you specified, then it runs your code. Then it takes the next item from the list and assign it to the same variable, then it runs your code again. And it keeps doing this until it has gone though all of the items in the list.

Which means that loops allow you to very easily run a block of code on all of the items in a list.

The structure for a for loop looks like this:

for VARIABLE in LIST:
    # Code to run

Where VARIABLE is the variable that the for loops assigns items to and LIST is the list it takes items from.

So to pass the first task of printing all of the items in the items list you simply need to type this:

def loopy(items):
    for item in items: # Pull items from `items` and assign it to item
        print(item)

Don't forget to put a : (colon) after the for loop declaration, and to indent (horizontally space) the code that follows it. In Python the indentation is used to group your code, so it has to be indented for Python to know that the code belongs to the for loop.

If you struggle with the second task as well then just post a reply asking for help and I'll gladly assist you.

Conner Williams
Conner Williams
Courses Plus Student 3,305 Points

I took some time away from this challenge and think I'm getting closer but I still cant figure out how to properly complete the second half of the exercise. This is the last bit of code I tried.

def loopy(items): for item in items: new_item = input('> ') if new_item == 'STOP': break print(item)

Conner Williams
PLUS
Conner Williams
Courses Plus Student 3,305 Points

I thought I knew how to break the loop and complete the second task. I feel like something might be wrong with my indenting?