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

Kyle Sass
Kyle Sass
902 Points

How to break a for loop in a function

Please help me break the for loop at STOP. I can't figure out what's wrong

breaks.py
def loopy(items):
    # Code goes here
    for item in items:
        print(items)
        if item == 'STOP':
            break

1 Answer

Steven Parker
Steven Parker
231,236 Points

The part the breaks the loop is OK, but if you want the loop to end before it prints out the word "STOP", you'd need to place the test and break above the "print" statement.

Kyle Sass
Kyle Sass
902 Points

'''def loopy(items):''' ''' # Code goes here''' ''' for item in items:''' ''' if item == 'STOP':''' ''' break''' ''' print(items)'''

I tried doing it like this but it's still not working, it says it didn't find the right items being printed. Here are it's instructions: I forgot that I need to break out of the loop when the current item is the string "STOP". Help me add that code!

Steven Parker
Steven Parker
231,236 Points

The order seems OK, but there could be an indentation issue, which cannot be seen without proper formatting. Use the instructions for code formatting in the Markdown Cheatsheet pop-up below the "Add an Answer" area. :arrow_heading_down:   Or watch this video on code formatting.