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

Break function in an assignment

I received an assignment from Phase 4 of Python basics tasks 2/2 after the first video. It asks me to break out of a loop once the current item is STOP. I tried but I am not getting the right results. Please Help!

breaks.py
def loopy(items):
    print(items) 

    for items == "STOP":
        break

your code should look like this. def loopy(items): for item in items: if item == "STOP": break print(item) Well just make sure that everything blocks their indentation are right.

Sorry, it doesn't work. @ Yamil Perez

1 Answer

Jeffrey James
Jeffrey James
2,636 Points

So keep in mind what you're iterating over. You have a bunch of items in the list. You iterate over them in order. Within the loop, you need to identify your break condition, which will be if the item is 'stop', or whatever. If that condition hits, then call break, else print out or do whatever to the item.

Here's an example:

In [1]: items = ['go', 'goo', 'goooo', 'stop', 'restart']

In [2]: for x in items:
   ...:     if x is 'stop':
   ...:         break
   ...:     print(x)
   ...:     
go
goo
goooo

A more sophisticated way of perhaps filtering your items without a loop: (still using our items list)

In [3]: [x for x in items if x is not 'stop']
Out[3]: ['go', 'goo', 'goooo', 'restart']

Even more obscure, but a pattern you may see in the wild: (still using our items list)

In [5]: list(filter(lambda x: x is not 'stop', items))
Out[5]: ['go', 'goo', 'goooo', 'restart']

Notice how in the break case above, you never reach an item after the break condition was reached, but when you're filtering using a list comprehension [3] or a filter expression [5], you safely pass over the unwanted item.